0

I have a nested dictionary in python e.g.

data_to_try = {1: {   'apples': 3,
        'bananas':5,
        'kiwis':9},
        2: {    'apples':9,
        'oranges':3,
        'kiwis':1},
       3: {    'apples': 6,
        'watermelon':9}}

I would like to plot bar charts with labeling of numerical values for each of the key in the nested dictionary. Note that the keys here are not same in all dictionaries. Secondly, I would like to keep the color specific to each key. I look forward to your kind feedback.

The present solution via another post of the stackoverflow can work only when the keys are same and equal in number of amount.

import numpy as np
import matplotlib.pyplot as plt
data = {'A': { 'apples':5,
        'oranges':6,
        'kiwis':9},
     
'B': {    'apples': 1,
        'oranges':9,
        'kiwis':3},
     
'C': {    'apples': 6,
        'oranges':9,
       'kiwis':9}}

solution is given below to this simple probelm

fig, ax = plt.subplots()

width = 0.2

ax.bar(np.arange(3)-width, [d[j]["apples"] for j in d], width,color = 'b',align = 'center')
ax.bar(np.arange(3), [d[j]["oranges"] for j in d], width, color = 'r',align = 'center')
ax.bar(np.arange(3)+width , [d[j]["kiwis"] for j in d], width,color = 'g',align = 'center')

ax.set_xticks(np.arange(3))
ax.set_xticklabels(["A", "B", "C"])
plt.show()

Plot may look like somewhat below, but as per data_to_try enter image description here

ali
  • 61
  • 2
  • 9
  • Why don't you restructure your data the way you need it first and then use that for plotting. Since you have dataframe as flag, you could use pandas DataFrame to hold the data. From your question it is not clear how the plot should look like. – FordPrefect May 21 '23 at 06:22
  • Good question. I can may be fix the first key (apples in this case), but that's actually a task in hand, I may have different second and third keys and sometimes only two keys instead of three. Still, I would like to have a single specific color to each key e.g. apples get blue, bananas get red color etc. in label bar charts. – ali May 21 '23 at 08:42
  • Still not clear, how your plot should look like. What is the meaning of the top level keys? Are they limited? Wouldn't it be better to have actual subplots? What do you want to read from the plot. Additionally you may have a look at seaborn. – FordPrefect May 21 '23 at 08:55
  • The top level keys are the numerical values of x-axis you can say. These are limited to 10 values let's say. Individual subplots are less preferable in this case for me as I want to show the trend by showing bars in single figure. Thanks for suggestions, I will look into seaborn and dataframe. I have edited how the result may look like. – ali May 21 '23 at 16:35
  • You should use pandas: Create the dataframe `df = pd.DataFrame(data)`, Plot `ax = df.plot(kind='bar', rot=0)`, Annotate `for c in ax.containers: ax.bar_label(c, fmt=lambda x: x if x > 0 else '')` see [How to add value labels on a bar chart](https://stackoverflow.com/a/67561982/7758804) – Trenton McKinney May 21 '23 at 16:35
  • See [code and plot](https://i.stack.imgur.com/fj75R.png) – Trenton McKinney May 21 '23 at 16:37
  • With or without pandas, the solution to add annotate the bars with labels is the same. – Trenton McKinney May 21 '23 at 16:40
  • See [code and plot](https://i.stack.imgur.com/7yzKK.png) of the second data. – Trenton McKinney May 21 '23 at 16:54
  • [plot bar plot from nested dictionary](https://stackoverflow.com/a/76301036/7758804) – Trenton McKinney May 21 '23 at 17:23

0 Answers0