Seaborn 条形图在不同高度添加水平线

Seaborn barplot add horizontal line at different heights

我有一个条形图,我想根据 pandas 列值在每个条形中添加一条水平线。我已经看到了如何在所有条上添加一条水平线的示例,但这不是我的目标。

目前我尝试过的是:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([[1, 2, 1], [2, 4, 3], [3, 6, 1], [4, 8, 3]], columns=["X", "Value", "Hor"])
fig, ax = plt.subplots()
sns.barplot(x="X", y="Value", data=df, color='green', ax=ax)
sns.barplot(x="X", y="Hor", data=df, color='green', linewidth=2.5, edgecolor='black', ax=ax)

这与我想要的比较接近,但我只想要顶部边缘,最好是虚线。

我的问题是双重的:

  1. 这是这样做的方法吗?通过将两个条形图堆叠在一起?
  2. 如果是这样的话,我怎样才能调整所有的边缘以适应我的需要?

您可以迭代条形图中的补丁,提取宽度和位置并使用 plt.plot 绘制您的值。请注意,如果数据框未排序,这将中断。

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([[1, 2, 1], [2, 4, 3], [3, 6, 1], [4, 8, 3]], columns=["X", "Value", "Hor"])
fig, ax = plt.subplots()
sns.barplot(x="X", y="Value", data=df, color='green', ax=ax)

for ix, a in enumerate(ax.patches):
    
    x_start = a.get_x()
    width = a.get_width()
    
    ax.plot([x_start, x_start+width], 2*[df.loc[ix, 'Hor']], '--', c='k')

这可以在您的轴上使用 hlines 来实现,例如在遍历数据框的行时。代码如下所示:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([[1, 2, 1], [2, 4, 3], [3, 6, 1], [4, 8, 3]], columns=["X", "Value", "Hor"])

fig, ax = plt.subplots()
sns.barplot(x="X", y="Value", data=df, color='green', ax=ax)

# iterate over range of number of rows
for i in range(len(df)):
    ax.hlines(y = df.Hor[i], xmin = i-0.5, xmax = i+0.5,
              color = 'black')

绘制条形图时,第一个条形的 x 坐标从零开始,增量为 1。此信息可用于将 xminxmax 分配给 ax.hlines,此处采用 i 的形式,从零到数据框的行数减一.您可以根据需要自定义 0.5,具体取决于所需行的 'width'。