Plotting several plots in matplotlib using a list of dicts

Question:

I have a simple plot function:

def plot_data(dataset="boys", baby_name="David"):
    ax = dataset.T.sort_index().loc[:, baby_name].plot(legend = baby_name)

list_of_dict = [{"data": boys, "baby_name": "David",
                 "data": girls, "baby_name": "Susan",
                 "data": boys, "baby_name": "Colin",
                 "data": girls, "baby_name": "Frances"}]
for l in list_of_dict:
    ax = plot_data(l['data'], l['baby_name'])

I can layer up different plots by writing

ax = plot_data("boys", "David"])
ax = plot_data("boys", "Susan"])

But if I try to loop through the list and plot I only get one plot. Why is that?

The plot is what I’m trying to achieve.

enter image description here

Asked By: elksie5000

||

Answers:

Currently you’re redefining ax with each call to plot_data function. To retain the data across multiple calls to plot_data you need to define a top level ax and pass that as another parameter to plot_data. See for example this answer:

import matplotlib.pyplot as plt
df = pd.read_table('data', sep='s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)
Answered By: Ashwani Kumar

My way was to recognise that the data structure is a simply a list of dicts as alluded by both answers. I just changed the list and created a new dict for each. Simples.

list_of_dict = [{"data": boys, "baby_name": "David"},
                {"data": girls, "baby_name": "Susan"},
                {"data": boys, "baby_name": "Colin"},
                {"data": girls, "baby_name": "Frances"}]
for d in list_of_dict:
    ax = plot_data(d["data"], d["baby_name"])
Answered By: elksie5000
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.