如何在matplotlib两个y轴图表中对齐条形和线形? [英] How to align the bar and line in matplotlib two y-axes chart?
问题描述
我有一个熊猫df,如下所示:
I have a pandas df as below:
>>> df
sales net_pft sales_gr net_pft_gr
STK_ID RPT_Date
600809 20120331 22.1401 4.9253 0.1824 -0.0268
20120630 38.1565 7.8684 0.3181 0.1947
20120930 52.5098 12.4338 0.4735 0.7573
20121231 64.7876 13.2731 0.4435 0.7005
20130331 27.9517 7.5182 0.2625 0.5264
20130630 40.6460 9.8572 0.0652 0.2528
20130930 53.0501 11.8605 0.0103 -0.0461
然后df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)
创建条形图.
和df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True)
创建折线图:
现在,我想使用twinx()将它们放到两个y轴的图表中.
Now I want to put them together in a chart of two y-axes, using twinx().
import matplotlib.pyplot as plt
fig = plt.figure()
ax = df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)
ax2 = ax.twinx()
ax2.plot(df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0)
结果是这样的:
我的问题是:
- 如何在同一条x轴上移动直线以使其与条形对齐?
- 如何使左右y_axis标记在同一行上对齐?
推荐答案
只需将最后一行更改为:
Just change the final line to:
ax2.plot(ax.get_xticks(),
df[['sales_gr','net_pft_gr']].values,
linestyle='-',
marker='o', linewidth=2.0)
您会准备就绪的.
我不太明白你的第二个问题.第1和第2 y轴的比例不同,将它们对齐到同一行是什么意思?它们不能与同一条网格线对齐(是的,可以,但是右轴看起来很难看,具有0.687之类的值).无论如何,您可以这样做:
I don't quite get your second question. The 1st and 2nd y axis are of different scale, what do you mean by aligning them to the same line? They can't be aligned to the same grid line (yes you can but the right axis will look ugly, having values like 0.687 and alike). Anyway, you can do:
ax.set_ylim((-10, 80.))
对齐它们,现在该图看起来很丑:
to align them, and the plot now looks ugly:
这篇关于如何在matplotlib两个y轴图表中对齐条形和线形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!