Matplotlib print values on bars in subplots

Question:

Using the above code, I have created 5 five subplots:

values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}

df = pd.DataFrame(data=values)

fig, axs = plt.subplots(2, 3, figsize=(10,6))

eu = axs[0, 0].bar(df["x_values"], df["eu"]
man = axs[0, 1].bar(df["x_values"], df["man"])
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
che = axs[1, 1].bar(df["x_values"], df["che"])
fig.delaxes(axs[1, 2])

They print as they should, but I also want to add to the bars the y value of every bar. Just like in the picture
enter image description here

I have tried the code below, but it doesn’t print anything, no error but also no print

for index, value in enumerate(df["corresponding_df"]):
    plt.text(value, index, str(value))

If I try variable-name.text(value, index, str(value)) I get error 'BarContainer' object has no attribute 'text'. If fig.text again not print. If axs[subplot-index].text I can only see a number at the end of the window outside the plots. Any suggestion?

Asked By: George M

||

Answers:

Try this using bar_label in matplotlib 3.4.0+:

values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}

df = pd.DataFrame(data=values)

fig, axs = plt.subplots(2, 3, figsize=(10,6))

eu = axs[0, 0].bar(df["x_values"], df["eu"])
axs[0,0].bar_label(eu)
man = axs[0, 1].bar(df["x_values"], df["man"])
axs[0,1].bar_label(man)
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
axs[0,2].bar_label(min3)
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
axs[1,0].bar_label(min4)
che = axs[1, 1].bar(df["x_values"], df["che"])
axs[1,1].bar_label(che)
fig.delaxes(axs[1, 2])

Output:

enter image description here

Answered By: Scott Boston

with texts it can be done like this:

for ax in axs.flatten():
    for bar in ax.patches:
        ax.text(bar.get_x() + bar.get_width() / 2, 
                bar.get_height()-7,
                bar.get_height(), 
                ha='center',
                color='w')

enter image description here

Answered By: SergFSM
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.