【问题标题】:How to build this specific graph?如何构建这个特定的图表?
【发布时间】:2020-12-21 10:32:51
【问题描述】:

我有这个数据库:

我想要一个几乎像这样的图形:

我是用这段代码获得的:

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

但是加上一个不错的小插件。拥有相应的意味着就在蓝色条计数右侧的末尾。 (也许 seaborn 更适合这个任务?)

你看到我想要什么了吗?如果没有,请告诉我,我会尽量做出更清楚的解释。

不管怎样,有什么想法吗?

【问题讨论】:

标签: python python-3.x matplotlib seaborn visualization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多