Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

python - How to align the bar and line in matplotlib two y-axes chart?

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

Then df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True) create bar chart.

And df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True) create line chart:

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)

The result is like this : enter image description here

My issues are:

  • How to shift the line to align with the bar at the same x-tickers ?
  • How to let the left and right y_axis tickers aligned at the same line?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

enter image description here

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...