python-novice-gapminder icon indicating copy to clipboard operation
python-novice-gapminder copied to clipboard

Update 09-plotting.md

Open annajiat opened this issue 4 years ago • 1 comments

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 (with plt.gcf) and call the savefig class 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.savefig seems 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 savefig class method from that variable.
fig = plt.gcf() # get current figure
data.plot(kind='bar')
fig.savefig('my_figure.png')

annajiat avatar Aug 12 '21 01:08 annajiat

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')

alee avatar Aug 16 '21 18:08 alee