Update 09-plotting.md
In "plotting" episode, at https://swcarpentry.github.io/python-novice-gapminder/09-plotting/index.html#:~:text=When%20using%20dataframes under "Saving your plot to a file", the workaround to use the variable and calling fig.savefig() no longer works and generates empty file. However, the original solution plt.savefig() works now. We can choose to keep the example for the idea of using a variable.
Proposed:
When using dataframes, data is often generated and plotted to screen in one line. In addition to using
plt.savefig, we can save a reference to the current figure in a local variable (withplt.gcf) and call thesavefigclass method from that variable to save the figure to file.data.plot(kind='bar') fig = plt.gcf() # get current figure fig.savefig('my_figure.png')
Existing:
When using dataframes, data is often generated and plotted to screen in one line, and
plt.savefigseems not to be a possible approach. One possibility to save the figure to file is then to
- save a reference to the current figure in a local variable (with
plt.gcf)- call the
savefigclass method from that variable.fig = plt.gcf() # get current figure data.plot(kind='bar') fig.savefig('my_figure.png')
Thanks for discovering this! I just tried testing this and on my system it looks like it works if you just run a plt.savefig right after a plot command, e.g.,
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('data/gapminder_all.csv', index_col='country')
data.plot(kind='scatter', x='gdpPercap_2007', y='lifeExp_2007', s=data['pop_2007']/1e6)
plt.savefig('all_data.png')