您可以遍历生成的条形(矩形)并获取它们的坐标以用于添加文本。条形颜色也可以根据'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()