Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add values over each bar in stacked bar plot

I have the following data:

similarity_score_summary={'sim_model':['jaccard_sim','Cos_tfidf_sim','spacy_sim','sent_trf_sim','wv_gensim_sim'],
                          'acc(thres=0.5)':[0.65,0.66,0.38,0.62,0.39],
                          'acc(thres=0.75)':[0.61,0.62,0.41,0.79,0.44],
                          'acc(thres=0.90)':[0.62,0.62,0.60,0.76,0.55]
                }

df_sim = pd.DataFrame.from_dict(similarity_score_summary)
# setting first name as index column 
df_sim.set_index("sim_model", inplace = True) 

fig=plt.figure(figsize=(10, 8))
axes=fig.add_subplot(1, 1, 1)
bar_width = 0.3
idx = np.array(range(df_sim.shape[0]))
labels = df_sim.index
plt.bar(data=df_sim, height='acc(thres=0.5)', x=idx, color='b', width=bar_width, label='acc(thres=0.5)')
plt.bar(data=df_sim, height='acc(thres=0.75)', x=idx+bar_width, color='g', width=bar_width, label='acc(thres=0.75)')
plt.bar(data=df_sim, height='acc(thres=0.90)', x=idx+bar_width+bar_width, color='magenta', width=bar_width, label='acc(thres=0.90)')
plt.xticks(idx, labels, rotation=90)
plt.xlabel('Similarity methods')
plt.ylabel('Similarity Score')
plt.ylim((0, 1))
plt.title('Accuracy score for different Similarity methods on Quora Question pairs Kaggle data')
plt.legend(['thres=0.5', 'thres=0.75', 'thres=0.9'], loc='upper right', ncol = 3)
plt.show()

This results in below fig:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to add values on top of each bar. Need help?

>Solution :

Define bars, iterate over them and get height of each bar, get x value and use plt.text to add value above each bar.

Example:

bar1 = plt.bar(
    data=df_sim,
    height="acc(thres=0.5)",
    x=idx,
    color="b",
    width=bar_width,
    label="acc(thres=0.5)",
)
bar2 = plt.bar(
    data=df_sim,
    height="acc(thres=0.75)",
    x=idx + bar_width,
    color="g",
    width=bar_width,
    label="acc(thres=0.75)",
)
bar3 = plt.bar(
    data=df_sim,
    height="acc(thres=0.90)",
    x=idx + bar_width + bar_width,
    color="magenta",
    width=bar_width,
    label="acc(thres=0.90)",
)
for bars in [bar1, bar2, bar3]:
    for bar in bars:
        yval = bar.get_height()
        plt.text(bar.get_x(), yval + 0.005, yval)

Result:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading