我有一个数据框,其中有3列:其中一列是“groupby”列,另外两列是具有值的“normal”列。我想生成一个箱线图和一个柱状图。在柱状图上,我希望可视化每个组元素出现的次数。让我的样例代码更详细地描述这个数据框:
li_str = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
df = pd.DataFrame([[i]+j[k] for i,j in {li_str[i]:np.random.randn(j, 2).tolist() for i,j in \
enumerate(np.random.randint(5, 15, len(li_str)))}.items() for k in range(len(j))]
, columns=['A', 'B', 'C'])
所以,我对li_str
中的每个元素生成随机数量的随机值,并将其应用于列B
和C
。
然后,我只可视化一个箱线图:
fig, ax = plt.subplots(figsize=(16,6))
p1 = df.boxplot(ax=ax, column='B', by='A', sym='')
我的结果是: 现在我可视化每个组所拥有的元素数量(使用上面的代码
np.random.randint(5, 15, len(li_str))
生成的随机数):fig, ax = plt.subplots(figsize=(16,6))
df_gb = df.groupby('A').count()
p2 = df_gb['B'].plot(ax=ax, kind='bar', figsize=(16,6), colormap='Set2', alpha=0.3)
plt.ylim([0, 20])
我的结果是: 现在我想把这两个图表合并成一个:
fig, ax = plt.subplots(figsize=(16,6))
ax2 = ax.twinx()
df_gb = df.groupby('A').count()
p1 = df.boxplot(ax=ax, column='B', by='A', sym='')
p2 = df_gb['B'].plot(ax=ax2, kind='bar', figsize=(16,6)
, colormap='Set2', alpha=0.3, secondary_y=True)
plt.ylim([0, 20])
我的结果是: 有人知道为什么我的箱线图会向右偏移一个x轴刻度吗?我使用的是Python 3.5.1,pandas 0.17.0,matplotlib 1.4.3。
谢谢!!!
plt.plot()
还是pandas的df.plot()
都不起作用。更好地说,我无法为这些函数指定xticks :( - ragesz