I have a pandas df as below:
我有一个熊猫df如下:
>>> 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
Then df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)
create bar chart.
然后df[[‘销售’,‘net_pft]].unstack(“STK_ID”)。绘图(kind='bar', use_index=True)创建条形图。
And df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True)
create line chart:
和df[[‘sales_gr’,‘net_pft_gr]]。plot(kind='line', use_index=True)创建行图:
Now I want to put them together in a chart of two y-axes, using twinx().
现在我想用twinx()将它们放在两个y轴的图表中。
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)
The result is like this :
结果是这样的:
My issues are:
我的问题是:
- How to shift the line to align with the bar at the same x-tickers ?
- 如何在相同的x-tickers中改变直线与杆的对齐方式?
- How to let the left and right y_axis tickers aligned at the same line?
- 如何让左和右的y_axis标记对齐到同一行?
1 个解决方案
#1
7
Just change the final line to:
只要把最后一行改为:
ax2.plot(ax.get_xticks(),df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0)
You will be all set.
你们都准备好了。
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:
我不太明白你的第二个问题。第一个和第二个y轴是不同比例的,你把它们对齐到同一条线上是什么意思?它们不能与相同的网格线对齐(是的,可以,但是右轴看起来很难看,值为0.687之类)。无论如何,你能做什么:
ax.set_ylim((-10, 80.))
to align them, and the plot now looks ugly:
如果把它们对齐,现在的情节看起来很丑陋:
#1
7
Just change the final line to:
只要把最后一行改为:
ax2.plot(ax.get_xticks(),df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0)
You will be all set.
你们都准备好了。
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:
我不太明白你的第二个问题。第一个和第二个y轴是不同比例的,你把它们对齐到同一条线上是什么意思?它们不能与相同的网格线对齐(是的,可以,但是右轴看起来很难看,值为0.687之类)。无论如何,你能做什么:
ax.set_ylim((-10, 80.))
to align them, and the plot now looks ugly:
如果把它们对齐,现在的情节看起来很丑陋: