Matplotlib:使用twinx叠加时,框图和条形图发生了移动 [英] Matplotlib: Boxplot and bar chart shifted when overlaid using twinx

查看:14
本文介绍了Matplotlib:使用twinx叠加时,框图和条形图发生了移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建条形图并使用TWIN X覆盖条形图时,与条形图相比,框看起来向右移动了一位。

以前已发现此问题(Python pandas plotting shift x-axis if twinx two y-axes),但解决方案似乎不再起作用。(我正在使用Matplotlib 3.1.0)

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

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

输出显示,与条形图相比,框向右移动了一位。上一篇帖子的回复者正确地指出,条形图的刻度位置是从零开始的,而方框的刻度位置是从一开始的,这就是造成这种变化的原因。但是,被调查者用来修复它的plt.bar()方法现在抛出了一个错误,因为x参数已被强制设置。如果提供了x参数,它仍然会抛出错误,因为不再有‘Left’参数。

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)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-186-e257461650c1> in <module>
     26 plt.twinx()
     27 plt.bar(left=plt.xticks()[0], height=df.groupby('A').count()['B'],
---> 28         align='center', alpha=0.3)

TypeError: bar() missing 1 required positional argument: 'x'

此外,我更喜欢使用面向对象的方法对轴进行修复,因为我想将图表放到一个交互式ipywidget中。

以下是理想的图表:

非常感谢。

推荐答案

您可以使用以下技巧:提供从x=1开始放置条形图的x值。为此,请使用range(1, len(df_gb['B'])+1)作为x值。

fig, ax = plt.subplots(figsize=(8, 4))
ax2 = ax.twinx()
df_gb = df.groupby('A').count()
df.boxplot(column='B', by='A', ax=ax)
ax2.bar(range(1, len(df_gb['B'])+1), height=df_gb['B'],align='center', alpha=0.3)

这篇关于Matplotlib:使用twinx叠加时,框图和条形图发生了移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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