Seaborn Barplot – Displaying Values

New in matplotlib 3.4.0

There is now a built-in Axes.bar_label to automatically label bar containers:

  • For single-group bar plots, pass the single bar container:

    ax = sns.barplot(x='day', y='tip', data=groupedvalues)
    ax.bar_label(ax.containers[0])
    

    seaborn bar plot labeled

  • For multi-group bar plots (with hue), iterate the multiple bar containers:

    ax = sns.barplot(x='day', y='tip', hue="sex", data=df)
    for container in ax.containers:
        ax.bar_label(container)
    

    seaborn grouped bar plot labeled

More details:

  • How to label count plots (sns.countplot and sns.catplot)
  • How to label percentage counts (fmt param)
  • How to label with commas as thousands separators (labels param)
  • How to label thresholded bar plots
  • How to label horizontal bar plots

Color-ranked version

Is there a way to scale the colors of the bars, with the lowest value of total_bill having the lightest color (in this case Friday) and the highest value of total_bill having the darkest?

  1. Find the rank of each total_bill value:

    • Either use Series.sort_values:

      ranks = groupedvalues.total_bill.sort_values().index
      # Int64Index([1, 0, 3, 2], dtype="int64")
      
    • Or condense Ernest’s Series.rank version by chaining Series.sub:

      ranks = groupedvalues.total_bill.rank().sub(1).astype(int).array
      # [1, 0, 3, 2]
      
  2. Then reindex the color palette using ranks:

    palette = sns.color_palette('Blues_d', len(ranks))
    ax = sns.barplot(x='day', y='tip', palette=np.array(palette)[ranks], data=groupedvalues)
    

    seaborn bar plot color-ranked

Leave a Comment

tech