Reputation: 57
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
Thanks for the help!
Upvotes: 1
Views: 872
Reputation: 62393
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()
Upvotes: 2