AndreyIto
AndreyIto

Reputation: 974

Matplotlib: subplot bar charts with with height labels

I have a dataframe, df, like:

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

I want to plot two vertical bar charts, one for each continent, side by side, sharing the same y axis. I've gotten 90% of the way, except for adding the heights of the bars to the subplots. My code so far:

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()

I've seen examples here and there with labels, but these tend to apply to just one bar chart, not several subplots.

Upvotes: 1

Views: 2150

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169534

You could do this with only a slight modification to your code. Using this answer: 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')

Upvotes: 1

Related Questions