I have a barplot and I would like to add a horizontal line in each of the bars based on a pandas column value. I have seen examples of how to add a single horizontal line over all the bars but this is not what I am aiming for.
What I have tried so far is:
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)
This is relatively close to what I would like to have, but I only want the top edge and preferably dashed.
My question is twofold:
- Is this the way to do this? By stacking two barplots on top of each other?
- If this is the way, how can I adjust all the edges to fit what I need?
CodePudding user response:
You can iterate over the patches in your barplot, extract width and position and plot your values using plt.plot. Note that this will break if the dataframe is not sorted.
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')
CodePudding user response: