python - Matplotlib:带有高度标签的子图条形图

标签 python matplotlib

我有一个数据框 df,例如:

continent | country   | counts
------------------------------
East Asia | Hong Kong | 33
East Asia | Japan     | 51
Europe    | Austria   | 10
Europe    | Belgium   | 3
Europe    | Denmark   | 15

我想绘制两个垂直条形图,每个大陆一个,并排绘制,共享相同的 y 轴。除了将条形的高度添加到子图中之外,我已经完成了 90%。到目前为止我的代码:

continents_ls = list(set(df["continent"]))
# continents_ls = ["East Asia", "Europe"]

fig, ax = plt.subplots(1, len(continents_ls), figsize=(30, len(continents_ls)*5), sharey=True)

for i in range(len(continents_ls)):
    d_temp = df.loc[df["continent"] == continents_ls[i]].groupby("country").size().to_frame().reset_index()
    # d_temp is the partition containing info for just one continent
    d_temp.columns = ["country", "count"] # name the 'count' column
    idx = list(d_temp["country"]) # get the list of countries in that continent
    ht_arr = list(d_temp["count"])
    ax[i].bar(left=range(len(ht_arr)), height=ht_arr)
    ax[i].set_xticks(np.arange(len(idx)))
    ax[i].set_xticklabels(idx, size=8, rotation=45)
    ax[i].set_title(continents_ls[i], size=23)
    ax[i].set_yticklabels(ht_arr, minor=False)

plt.tight_layout()
plt.show()

我到处都看到过带有标签的示例,但这些示例往往仅适用于一个条形图,而不是多个子图。

最佳答案

只需对代码稍作修改即可实现此目的。使用这个答案:https://stackoverflow.com/a/34598688/42346

for i in range(len(continents_ls)):
    d_temp = df.loc[df["continent"] == continents_ls[i]].groupby("country").size().to_frame().reset_index()
    # d_temp is the partition containing info for just one continent
    d_temp.columns = ["country", "count"] # name the 'count' column
    idx = list(d_temp["country"]) # get the list of countries in that continent
    ht_arr = list(d_temp["count"])
    ax[i].bar(left=range(len(ht_arr)), height=ht_arr)
    ax[i].set_xticks(np.arange(len(idx)))
    ax[i].set_xticklabels(idx, size=8, rotation=45)
    ax[i].set_title(continents_ls[i], size=23)
    ax[i].set_yticklabels(ht_arr, minor=False)
    if i == 0: # only for the first barplot
      for p in ax[i].patches:
        ax[i].annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

关于python - Matplotlib:带有高度标签的子图条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43508080/

相关文章:

python - Pygame 按钮单击

python - 带有 xdist 的 py.test 没有执行用随机值参数化的测试

python - Matplotlib 离线绘图

python - 散点图无法正确调整 matplotlib 中的绘图范围

python - Python 中的简约实时绘图

python - 500 内部服务器错误 : Python Bottle API

python - pyad:安装正常,但说找不到 adbase

python - 使用 tf-idf 的文档之间的余弦相似度和 TS-SS 相似度 - Python

python - 使用 matplotlib 同时绘制两个函数

python - 基于字符串值列表的条形图