python - Matplotlib,从 pandas 数据帧在 barplot 上绘制多个单独的 hline

标签 python pandas matplotlib plot

我有一个简单的 pandas 数据框和绘图,如下所示:

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

test_df_1 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))
test_df_1.plot(kind='bar')

这会产生以下图:

enter image description here

然后我有另一个数据框:

test_df_2 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))

这与我的第一个数据框的尺寸相同。我希望在顶部绘制简单的水平线,如以下模型:

enter image description here

我该如何实现这一目标?我知道 axhline 但我不知道如何在这种情况下应用它来实现我想要的。

最佳答案

我想不出更好的方法,但你可以从ax.patches获取柱的信息:

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

test_df_1 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))
ax = test_df_1.plot(kind='bar')
test_df_2 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))

x = np.array([r.get_x() for r in ax.patches])
w = np.array([r.get_width() for r in ax.patches])

ax.hlines(test_df_2.values.T.ravel(), x, x + w, color="red", lw=2)

这是输出:

enter image description here

关于python - Matplotlib,从 pandas 数据帧在 barplot 上绘制多个单独的 hline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121309/

相关文章:

python - OpenCV 中保存的 webp 图像比 jpg 大 3 倍

python - 如何在Power BI中激活Python虚拟环境?

python - 如何在 Pandas 中重写 Oracle 合并?

python - 将 HTML 表放入 pandas Dataframe,而不是 dataframe 对象列表

python - 从消耗时间的项目和不消耗时间但仍需要绘制空间的项目生成基于时间线的线性表示

python - Django 登录表单输入字段未显示

python - 在 SeriesGroupBy 上执行 apply() 后如何将我的 Series 设为 "re-group"?

python - Matplotlib图散点图

python - 如何显示每个Y轴的图表类型以区分比较因素

python-3.x - 分别设置两个直方图的颜色有问题