DouglasFalcon
DouglasFalcon

Reputation: 41

How to build this specific graph?

I have this database :

data

And I would like a graphe almost like that :

graphe

I obtained it with this code :

plt.figure(figsize = (10,8))
plt.barh(trigram['Text'], trigram['count'])
plt.title('Top 20 Trigrams in Gamm Vert');

But with a nice little add on it. Having the respectives means just at the end of the right side of the blue bar count. (maybe seaborn is more suitable for this task ?)

Do you see what I want ? If not, tell me, I will try to make clearer explanations.

Anyway, any ideas how to do that ?

Upvotes: 0

Views: 68

Answers (1)

JohanC
JohanC

Reputation: 80359

You can loop through the generated bars (rectangles) and get their coordinates to be used to add a text. The bar colors also could be changed depending on the 'mean':

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# first generate some toy data
N = 20
trigram = pd.DataFrame({'Text': ["".join(np.random.choice([*'abcdef '], np.random.randint(10, 20))) for _ in range(N)],
                        'count': np.random.randint(100, 150, N),
                        'means': np.random.uniform(1.4, 4.6, N)})
trigram.sort_values('count', ascending=True, inplace=True)

plt.figure(figsize=(10, 8))
bars = plt.barh(trigram['Text'], trigram['count'])
plt.title('Top 20 Trigrams in Gamm Vert')
cmap = plt.get_cmap('RdYlBu') # red, yellow, blue
for bar, mean in zip(bars, trigram['means']):
    y = bar.get_y() + bar.get_height() / 2
    x = bar.get_width()
    plt.text(x, y, f' {mean:.2f}', ha='left', va='center')
    bar.set_color(cmap(mean / 5))  # redlike for low values, blue like for high values
plt.margins(x=0.15, y=0.02)  # more space for the text, less vertical white space
plt.tight_layout()  # fit the tick labels into the image
plt.show()

example plot

Upvotes: 3

Related Questions