python pandas 绘制两个y轴的偏移x轴 [英] Python pandas plotting shift x-axis if twinx two y-axes

查看:297
本文介绍了python pandas 绘制两个y轴的偏移x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe with 3 columns: one of them is a "groupby" column, the other two are "normal" columns with values. I want to generate a boxplot and a bar chart as well. On the bar chart I want to visualize the number of occurences of each group's element. Let my sample code tell this dataframe in more detailed:

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执行此操作.

So above I generate random number of random values to every element in li_str and I do it for columns Band C.

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

Then I visualize only a boxplot:

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))代码生成的随机数):

Now I visualize the number of elements every group has (so the random numbers I generated above with np.random.randint(5, 15, len(li_str)) code):

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

我的结果是:

现在我希望将这两个图合在一张图中:

And now I want these two in one diagram:

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

Does anybody know why my boxplot is shifted to right with one x-axis tick? I use Python 3.5.1, pandas 0.17.0, matplotlib 1.4.3

谢谢!

推荐答案

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

It's because the boxplot and the bar plot do not use the same xticks even if the labels are the same.

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()中修复,但是我可能只是忽略了原理.

At a glance it looks to me like an inconsistency which should be fixed in matplotlib boxplot(), but I might just be overlooking the rationale.

作为解决方法,请使用matplotlib bar(),它允许您指定xticks以匹配箱线图(我没有找到使用df.plot(kind='bar')的方法.

As a workaround use matplotlib bar(), that allows you to specify the xticks to match those of the boxplot (I did not found a way to do it with 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)

这篇关于python pandas 绘制两个y轴的偏移x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆