Home > database >  pandas: draw plot using dict and labels on top of each bar
pandas: draw plot using dict and labels on top of each bar

Time:01-21

I am trying to plot a graph from a dict, which works fine but I also have a similar dict with values that I intend to write on top of each bar.

This works fine for plotting the graph:

import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['axes.formatter.useoffset'] = False

df = pd.DataFrame([population_dct])
df.sum().sort_values(ascending=False).plot.bar(color='b')
plt.savefig("temp_fig.png")

Where the population_dct is:

{'pak': 210, 'afg': 182, 'ban': 94, 'ind': 32, 'aus': 14, 'usa': 345, 'nz': 571, 'col': 47, 'iran': 2}

Now I have another dict, called counter_dct:

{'pak': 1.12134, 'afg': 32.4522, 'ban': 3.44, 'ind': 1.123, 'aus': 4.22, 'usa': 9.44343, 'nz': 57.12121, 'col': 2.447, 'iran': 27.5}

I need the second dict items to be shown on top of each bar from the previous graph.

What I tried:

df = pd.DataFrame([population_dct])
df.sum().sort_values(ascending=False).plot.bar(color='g')
for i, v in enumerate(counter_dct.values()):
     plt.text(v, i, " "   str(v), color='blue', va='center', fontweight='bold')

This has two issues:

  1. counter_dct.values() msesses up with the sequence of values
  2. The values are shown at the bottom of each graph with poor alignment

Perhaps there's a better way to achieve this?

CodePudding user response:

Since you are drawing the graph in a desc manner;

You need to first sort the population_dict in a desc manner based on values

temp_dct = dict(sorted(population_dct.items(), key=lambda x: x[1], reverse=True))

Start with the temp_dct and then get the value from the counter_dct

counter = 0 # to start from the x-axis
for key, val in temp_dct.items():
    top_val = counter_dct[key]
    plt.text(x=counter, y=val   2, s=f"{top_val}", fontdict=dict(fontsize=11))
    counter  = 1
plt.xticks(rotation=45, ha='right')
  • Related