Question

How to plot justify bar labels to the right side and add a title to the bar labels in Python's matplotlib?

I have created a chart in matplotlib in python, but the last line in the following code doesn't allow alignment of the bar labels outside of the graph.

import matplotlib.pyplot as plt
g=df.plot.barh(x=name,y=days)
g.set_title("Days people showed up")
g.bar_label(g.containers[0], label_type='edge')

I get a graph that looks like:

      Days people showed up
     -----------------------
Amy  |+++ 1                |
Bob  |+++++++++++++++ 4    |
Jane |+++++++ 2            |
     ---|---|---|---|---|---
        1   2   3   4   5

Instead I want something like this:

      Days people showed up
     ----------------------- Count
Amy  |+++                  |     1
Bob  |+++++++++++++++      |     4
Jane |+++++++              |     2
     ---|---|---|---|---|---
        1   2   3   4   5

Is it possible to do this? It doesn't seem like it is native in matplotlib as the only options for label_type is edge or center. Is it possible to add a label to the bar labels as well?

 3  39  3
1 Jan 1970

Solution

 1

You can use a "secondary y axis" (this is similar to the more often used "twin" axis, but is only used to add ticks and labels, not for plotting).

The example below uses ax as the name for the return value or df.plot.barh() to make the code easier to match with matplotlib documentation and tutorials. For more finetuning, ax.set_ylabe() has parameters to change its position and alignment.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'name': ['Amy', 'Bob', 'Jane'], 'days': [1, 4, 2]})
ax = df.plot.barh(x='name', y='days', legend=False)
ax.set_title("Days people showed up")
# ax.bar_label(ax.containers[0], label_type='edge')

secax = ax.secondary_yaxis(location='right', functions=(lambda x: x, lambda x: x))
secax.set_yticks(range(len(df)), df['days'])
secax.tick_params(length=0)
secax.set_ylabel('Counts')

plt.tight_layout()
plt.show()

adding barh information to the right of the plot

2024-07-24
JohanC