2017-04-20 46 views
1

我有一個數據幀,DF,如:Matplotlib:插曲條形圖與高度標記

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

只需稍微修改一下代碼即可。使用此答案: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')