Python 如何将 Pandas 饼图保存到文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32219350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:14:27  来源:igfitidea点击:

How to save Pandas pie plot to a file?

pythonpandasplot

提问by neversaint

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'

采纳答案by styvane

Well pieis a numpy array because the return type for DataFrame.plot()is a numpy array of matplotlib.AxesSubplotobjects.

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

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

回答by kxxoling

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.

声明:我的解决方案是保存在此处有效的当前绘图,但这不是执行此操作的好方法。@user3100115 发布的是正确的方法。

Using matplotlib.pyplot.savefigto save it:

使用matplotlib.pyplot.savefig来保存它:

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

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

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

pie plot

饼图

回答by Akash Nayak

Use this code:

使用此代码:

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

but make sure import shoul be like below code:

但确保导入应该像下面的代码:

import matplotlib.pyplot as plt