【问题标题】:How to save Pandas pie plot to a file?如何将 Pandas 饼图保存到文件中?
【发布时间】:2015-11-20 01:31:33
【问题描述】:

我有以下代码:

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

这使得饼图。我想要做的就是将它保存到一个文件中。 但是为什么会失败呢?

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

我收到此错误:

'numpy.ndarray' object has no attribute 'get_figure'

【问题讨论】:

    标签: python pandas plot


    【解决方案1】:

    pie 是一个 numpy 数组,因为 DataFrame.plot() 的返回类型是一个 matplotlib.AxesSubplot 对象的 numpy 数组。

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

    【讨论】:

      【解决方案2】:

      声明:我的解决方案是保存当前可用的绘图,但这不是一个好方法。 @user3100115 发布的内容是正确的做法。

      使用matplotlib.pyplot.savefig保存:

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

      您会得到一个名为 pie.png 的图像,如下所示:

      【讨论】:

      • @user3100115 那显然ndarray没有get_figure的功能,我想他真正想要的是成功保存图像吧?
      • 不,他正在尝试使用 DataFrame.plot() 绘制 DataFrame 对象,我已经发布了正确答案。
      【解决方案3】:

      使用此代码:

      plt.get.savefig('myplot') #figure will be saved as saved_figure.png
      plt.get.savefig('myplot.pdf') #figure will be saved as saved_figure.pdf
      

      但请确保导入应类似于以下代码:

      import matplotlib.pyplot as plt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-04
        • 2015-11-21
        • 2022-01-19
        • 2012-12-04
        • 1970-01-01
        • 2020-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多