pandas 熊猫箱线图作为具有单独 y 轴的子图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49690316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas boxplots as subplots with individual y-axis
提问by mati
Let's assume I have a dataframe with three groups 'K', 'L' and 'M' in column 'type' like:
假设我有一个数据框,在“type”列中包含三组“K”、“L”和“M”,例如:
df = pd.DataFrame(data={'A': random.sample(xrange(60, 100), 10),
'B': random.sample(xrange(20, 40), 10),
'C': random.sample(xrange(2000, 3010), 10),
'type': list(3*'K')+list(3*'L')+list(4*'M')})
For viewing single grouped boxplots I can use:
要查看单个分组的箱线图,我可以使用:
for i,el in enumerate(list(df.columns.values)[:-1]):
a = df.boxplot(el, by ='type')
I would now like to combine these single plots as subplots in one figure.
我现在想将这些单个图作为子图组合在一个图中。
Using df.boxplot(by='type')
creates such subplots. However, because of the variable range in column 'A', 'B' and 'C' these subplots are difficult to read, i.e. information is lost especially in printed forms.
使用df.boxplot(by='type')
创建这样的子图。然而,由于“A”、“B”和“C”列中的可变范围,这些子图难以阅读,即信息丢失,尤其是在印刷形式中。
How can each subplot have an individual y-axis?
每个子图如何具有单独的 y 轴?
回答by DavidG
A possible solution which also uses matplotlib
is to create the figure and subplots then pass the axes into df.boxplot()
using the argument ax=
也使用的一个可能的解决方案matplotlib
是创建图形和子图,然后df.boxplot()
使用参数将轴传递给ax=
For example:
例如:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,2) # create figure and axes
df = pd.DataFrame(data={'A': random.sample(xrange(60, 100), 10),
'B': random.sample(xrange(20, 40), 10),
'C': random.sample(xrange(2000, 3010), 10),
'type': list(3*'K')+list(3*'L')+list(4*'M')})
for i,el in enumerate(list(df.columns.values)[:-1]):
a = df.boxplot(el, by="type", ax=axes.flatten()[i])
fig.delaxes(axes[1,1]) # remove empty subplot
plt.tight_layout()
plt.show()