Python pandas绘图:如果使用twinx两个y轴,如何移动x轴?

4

我有一个数据框,其中有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中的每个元素生成随机数量的随机值,并将其应用于列BC

然后,我只可视化一个箱线图:

fig, ax = plt.subplots(figsize=(16,6))
p1 = df.boxplot(ax=ax, column='B', by='A', sym='')

我的结果是: enter image description here 现在我可视化每个组所拥有的元素数量(使用上面的代码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])

我的结果是: enter image description here 现在我想把这两个图表合并成一个:
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。
谢谢!!!
1个回答

3
这是因为箱线图和条形图即使标签相同,也不使用相同的x轴刻度。
df.boxplot(column='B', by='A')
plt.xticks()

(array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10]), <a list of 10 Text xticklabel objects>)

df.groupby('A').count()['B'].plot(kind='bar')
plt.xticks()

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), <a list of 10 Text xticklabel objects>)

一眼看上去,对我来说这似乎是一个需要在matplotlib的boxplot()中修正的不一致性问题,但我可能只是忽略了其合理性。
作为解决方法,可以使用matplotlib的bar(),它允许您指定xticks以匹配boxplot的xticks(我没有找到使用df.plot(kind='bar')实现此功能的方法)。
df.boxplot(column='B', by='A')
plt.twinx()
plt.bar(left=plt.xticks()[0], height=df.groupby('A').count()['B'],
        align='center', alpha=0.3)

enter image description here


谢谢您提供的有效解决方案。我的问题是,我现在想绘制平均线(它是一条简单的线),但是无论是matplotlib的plt.plot()还是pandas的df.plot()都不起作用。更好地说,我无法为这些函数指定xticks :( - ragesz
可以确认这个有效,我花了很多时间来解决这个问题。 - user1382854

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接