Home > Blockchain >  Seaborn barplot add horizontal line at different heights
Seaborn barplot add horizontal line at different heights

Time:10-30

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)

enter image description here

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:

  1. Is this the way to do this? By stacking two barplots on top of each other?
  2. 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')

enter image description here

CodePudding user response:

This can be achieved using Resulting plot

  • Related