28

I have the following code:

import pandas as pd
import matplotlib
matplotlib.style.use('ggplot')
df = pd.DataFrame({ 'sample1':['foo','bar','bar','qux'], 'score':[5,9,1,7]})
sum_df = df.groupby("sample1").sum()
pie = sum_df.plot(kind="pie", figsize=(6,6), legend = False, use_index=False, subplots=True, colormap="Pastel1")

Which makes the pie chart. What I want to do then is to save it to a file. But why this fail?

fig = pie.get_figure()
fig.savefig("~/Desktop/myplot.pdf")

I get this error:

'numpy.ndarray' object has no attribute 'get_figure'
styvane
  • 59,869
  • 19
  • 150
  • 156
neversaint
  • 60,904
  • 137
  • 310
  • 477

2 Answers2

33

Well pie is a numpy array because the return type for DataFrame.plot() is a numpy array of matplotlib.AxesSubplot objects.

fig = pie[0].get_figure()
fig.savefig("~/Desktop/myplot.pdf")
styvane
  • 59,869
  • 19
  • 150
  • 156
0

Claim: My solution is save the current plot which works here, but it's not a good way to do this. What @user3100115 posted is the right way to do this.

Using matplotlib.pyplot.savefig to save it:

import matplotlib.pyplot as plt
plt.savefig('pie')

You'll get a image named pie.png like this:

pie plot

Kane Blueriver
  • 4,170
  • 4
  • 29
  • 48
  • @user3100115 That's obviously ``ndarray`` does not have ``get_figure`` function, I think what he really want is to save the image successfully, right? – Kane Blueriver Aug 26 '15 at 07:05
  • 2
    NO he's trying to plot a `DataFrame` object using [`DataFrame.plot()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html) and I've posted the right answer. – styvane Aug 26 '15 at 07:09