Home > Net >  How to add column labels to graphs
How to add column labels to graphs

Time:03-22

I was wondering, if you can annotate every graph in this example automatically using the column headers as labels.

    import seaborn as sns
    import pandas as pd
    
    d = {'a': [100, 125, 300, 520],..., 'z': [250, 270, 278, 248]}
    df = pd.DataFrame(data=d, index=[25, 26, 26, 30])
             a    ...     z
  25        100   ...    250
  26        125   ...    270
  26        300   ...    278
  30        520   ...    248

When I use this code, I only get the column headers as a legend. However, I want the labels to be directly beside/above my graphs.

sns.lineplot(data=df, dashes=False, estimator=None)

CodePudding user response:

Is this what you are looking for?

ax = sns.lineplot(data=df, dashes=False, estimator=None, legend=False)

for label, pos in df.iloc[0].iteritems():
    ax.annotate(label, (df.index[0], pos*1.05), ha='left', va='bottom')

output:

annotated graph

CodePudding user response:

Something like:

ax = sns.lineplot(data=df, dashes=False, estimator=None)

for c, l in zip(df.columns, ax.lines):
    y = l.get_ydata()
    ax.annotate(f'{c}', xy=(1.01,y[-1]), xycoords=('axes fraction', 'data'), 
                ha='left', va='center', color=l.get_color())

enter image description here

Source: https://stackoverflow.com/a/62703420/15239951

  • Related