mat*_*ati 4 python boxplot pandas pandas-groupby
假设我有一个数据框,其“类型”列中包含三组“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')})
Run Code Online (Sandbox Code Playgroud)
为了查看单个分组的箱线图,我可以使用:
for i,el in enumerate(list(df.columns.values)[:-1]):
a = df.boxplot(el, by ='type')
Run Code Online (Sandbox Code Playgroud)
我现在想将这些单个图合并为一张图中的子图。
使用df.boxplot(by='type')创建这样的子图。然而,由于“A”、“B”和“C”列中的变量范围,这些子图难以阅读,即信息丢失,尤其是在印刷形式中。
每个子图如何拥有单独的 y 轴?
也使用的一种可能的解决方案matplotlib是创建图形和子图,然后df.boxplot()使用参数将轴传递给ax=
例如:
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()
Run Code Online (Sandbox Code Playgroud)