我有一个简单的 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')
这会产生以下图:
然后我有另一个数据框:
test_df_2 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))
这与我的第一个数据框的尺寸相同。我希望在顶部绘制简单的水平线,如以下模型:
我该如何实现这一目标?我知道 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)
这是输出:
关于python - Matplotlib,从 pandas 数据帧在 barplot 上绘制多个单独的 hline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121309/