How to plot nested dictionary using matplotlib (without using pandas)?

I have data structured similar to below, and I would like to plot it using matplotlib to create an image similar to the one below.

example = {2009:{'i': 260, 'like': 50, 'yeah': 115, 'food': 12},
           2010:{'i': 560,'like': 100, 'yeah': 215, 'food': 20},
           2011:{'i': 660, 'like': 200, 'yeah': 515, 'food': 25},
           2012:{'i': 1060, 'like': 100, 'yeah': 545, 'food': 5}}

and I want the output to be similar to

enter image description here

Thanks for the help!

Upvotes: 1

Views: 872

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62393

  • Caveat is that all inner dictionaries must have the same keys
  • map(str, example.keys()) converts the years from int to str, which will prevent the x-axis from looking like floats (e.g. 2009.0, 2009.5)
import matplotlib.pyplot as plt

# get inner keys
inner_keys = list(example.values())[0].keys()

# x-axis is the outer keys
x_axis_values = list(map(str, example.keys()))

# loop through inner_keys
for x in inner_keys:

    # create a list of values for inner key
    y_axis_values = [v[x] for v in example.values()]

    # plot each inner key
    plt.plot(x_axis_values, y_axis_values, label=x)

plt.legend()

enter image description here

Upvotes: 2

Related Questions