Matplotlib:使用Twinx叠加时,箱线图和条形图移动

时间:2019-08-12 18:45:34

标签: matplotlib boxplot twinx

当我创建一个barplot并使用双x叠加一个条形图时,与条形相比,这些框向右偏移一个。

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

String error = driver.findElement(By.cssSelector("div .flash")).getText().trim();
System.out.println(error);

The problematic chart

输出显示与条形框相比,框右移1个。前一篇文章的受访者正确地指出,条形的刻度位置是从零开始的,而框的刻度位置是从一个开始的,这引起了这种转变。但是,由于x参数已被强制使用,因此受访者用来修复它的String error = driver.findElement(By.xpath('//div[@class="container"]')).getText().trim(); System.out.println(error); 方法现在会引发错误。如果提供了x参数,则由于没有参数“ left”,它仍然会引发错误。

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

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

这是理想的图表:

Ideal chart

非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用以下技巧:提供x值,以放置从x=1开始的小节。为此,请使用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)

enter image description here