I would like to aggregate records by year in a dataframe and create (and save) a barchart for each of them.
Using my rudimentary python I create a dictionary grouping by year
dd = [x for _, x in df.groupby('year')]
The result is a dictionary ranging 0 to 55, which I can use to manually create a barchart. Of course I tried to create a basic loop to compute (and save) a barchart for each year
i = 0
for i in dd:
i = 1
title = dd[i]["year"].unique()[0]
plot = dd[i]['Journal Type'].value_counts().plot(kind='bar', title=title);
fig = plot.get_figure()
fig.savefig(str(title) '.png')
However, it save the first figure and that's it. What I am doing wrong? Any (more elegant) solution to the problem would be greatly appreciated
CodePudding user response:
I guess you need to create a new figure every time, also, why don't you just loop through the groupby
:
for title, data in df.groupby('year'):
fig, ax = plt.subplots()
data['Journal Type'].value_counts().plot(kind='bar', title=title, ax=ax)
fig.savefig(f'{title}.png')
plt.close(fig)