如何在一个轴上绘制两个barh?

时间:2016-03-02 01:27:23

标签: python pandas matplotlib plot

这是一个有超过500个项目的熊猫系列,我拿起前10和后10来绘制一个matplotlib轴,这是我手动绘制的图片:

sales of top 10 and bottom 10

数据在这里:

bottom10
Out[12]: 
0   -9.823127e+08
1   -8.069270e+08
2   -6.030317e+08
3   -5.709379e+08
4   -5.224355e+08
5   -4.755464e+08
6   -4.095561e+08
7   -3.989287e+08
8   -3.885740e+08
9   -3.691114e+08
Name: amount, dtype: float64

top10
Out[13]: 
0    9.360520e+08
1    9.078776e+08
2    6.603838e+08
3    4.967611e+08
4    4.409362e+08
5    3.914972e+08
6    3.547471e+08
7    3.538894e+08
8    3.368558e+08
9    3.189895e+08
Name: amount, dtype: float64



top10.barh(top10.index,top10.amount,color='red',align='edge')
bottom10.barh(bottom10.index,bottom10.amount,color='green',align='edge')

现在它显示如下,这不是我想要的: Not what I want

绘制正确的方法是什么?

1 个答案:

答案 0 :(得分:4)

您可以通过创建twiny轴并在其上绘制bottom10数据框来完成此操作。

例如:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Random data
bottom10 = pd.DataFrame({'amount':-np.sort(np.random.rand(10))})
top10 = pd.DataFrame({'amount':np.sort(np.random.rand(10))[::-1]})

# Create figure and axes for top10
fig,axt = plt.subplots(1)

# Plot top10 on axt
top10.plot.barh(color='red',edgecolor='k',align='edge',ax=axt,legend=False)

# Create twin axes
axb = axt.twiny()

# Plot bottom10 on axb
bottom10.plot.barh(color='green',edgecolor='k',align='edge',ax=axb,legend=False)

# Set some sensible axes limits
axt.set_xlim(0,1.5)
axb.set_xlim(-1.5,0)

# Add some axes labels
axt.set_ylabel('Best items')
axb.set_ylabel('Worst items')

# Need to manually move axb label to right hand side
axb.yaxis.set_label_position('right')

plt.show()

enter image description here