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

时间:2015-08-26 06:22:58

标签: python pandas plot

我有以下代码:

System.out.println(Float.parseFloat("Rs.99.99".substring(3)));

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

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

3 个答案:

答案 0 :(得分:17)

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

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

答案 1 :(得分:0)

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

使用<?php include "model/login_class.php"; include "view/template/product_class.php"; $tplLogin=new LoginTpl(); $sqlLogin=new sqlLogin(); //echo $_GET['page']; exit; $total_results = $sqlLogin->totalproduct(); $per_page = 5; $total_pages = ceil($total_results / $per_page); $tplLogin->total_pages = $total_pages; if (isset($_GET['page'])) { $show_page = $_GET['page']; //current page if ($show_page > 0 && $show_page <= $total_pages) { $start = ($show_page - 1) * $per_page; $end = $start + $per_page; } else { // error - show first set of results $start = 0; $end = $per_page; } } else { // if page isn't set, show first set of results $start = 0; $end = $per_page; } // display pagination $sqlLogin->start = $start; $sqlLogin->end = $end; $tplLogin->products = $sqlLogin->product(); $tplLogin->product(); ?> 进行保存:

matplotlib.pyplot.savefig

您将获得一张名为pie.png的图片:

pie plot

答案 2 :(得分:-2)

使用此代码:

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