Python pandas绘制移位x轴,如果是twx两个y轴

时间:2016-02-25 19:09:25

标签: python pandas plot axes

我有一个包含3列的数据框:其中一列是“groupby”列,另外两列是带有值的“普通”列。我想生成一个箱线图和一个条形图。在条形图上,我想要可视化每个组元素的出现次数。让我的示例代码更详细地告诉这个数据帧:

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])

我的结果是: enter image description here

有人知道为什么我的箱图会向右移动一个x轴勾号吗?我使用Python 3.5.1,pandas 0.17.0,matplotlib 1.4.3

谢谢!!!

1 个答案:

答案 0 :(得分:4)

这是因为即使标签相同,箱线图和条形图也不会使用相同的xticks。

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的那些(我没有找到与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