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

标签 python pandas matplotlib plot

这是一个包含 500 多个项目的 pandas 系列,我选择了前 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 .

什么是正确的绘图方式?

最佳答案

您可以通过创建一个twiny 轴,并在上面绘制bottom10 DataFrame 来实现这一点。

例如:

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

关于python - 如何在一个轴上绘制两个 barh?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736806/

相关文章:

python - Pandas 减去日期时间条件

python - 使用 sort_values() 独立地对 pandas DataFrame 的所有列进行排序

python - 使用 matplotlib 绘图 : hours shown as float

Python Pandas : rolling_kurt vs. scipy.stats.kurtosis

python - 非零值的 Numpy 平均值

Pandas 在两个分位数之间选择组中的值

Python Matplotlib : "ImportError: cannot import name flatten"

python - 使用样式表时自定义字体

python - python中的 boolean 递归

声明为 utf-8 的模块中的 Python unicode 字符串文字