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

时间:2017-04-20 00:09:37

标签: 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()

我在这里和那里看过带标签的例子,但这些只适用于一个条形图,而不是几个子图。

1 个答案:

答案 0 :(得分:1)

只需对代码稍作修改即可完成此操作。使用此答案: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')