pandas 将 dataframe.hist() 保存到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31596084/
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-09-13 23:40:24  来源:igfitidea点击:

save dataframe.hist() to a file

python-2.7numpypandasmatplotlib

提问by user36869

I am attempting to create a dataframe histogram and save it as a file.

我正在尝试创建数据帧直方图并将其另存为文件。

Here is my code:

这是我的代码:

ax=df.hist('ColumnName')
fig=ax.get_figure()
fig.savefig('pictureName.png', dpi=100, 
bbox_inches='tight')

The first line works fine; however, the second line returns an error: AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'.

第一行工作正常;但是,第二行返回错误:AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'。

Because this questionshows the get_figure() being applied to series.hist(), I have also tried using ax=df['ColumnName'].hist(), which successfully produced a histogram but led to the same error message when I attempted to implement get_figure().

因为这个问题显示了 get_figure() 应用于 series.hist(),我也尝试过 using ax=df['ColumnName'].hist(),它成功地生成了一个直方图,但在我尝试实现 get_figure() 时导致了相同的错误消息。

As recommended in this other question, normally I would skip the get_figure() and the fig.savefig(), opting instead for plt.savefig, but I am making multiple figures. In my experience, plt.savefig() is unreliable in saving multiple figures, instead saving one figure multiple times, even when I use fig.close() after each figure creation and save.

正如在另一个问题中所建议的那样,通常我会跳过 get_figure() 和 fig.savefig(),而是选择 plt.savefig,但我正在制作多个数字。根据我的经验,plt.savefig() 在保存多个图形时不可靠,而是多次保存一个图形,即使我在每个图形创建和保存后使用 fig.close() 也是如此。

I very much want to solve this problem as neatly as possible, so that I can carry the solution smoothly into other applications, rather than having to use a different duct-tape fix every time I have to make a graph.

我非常想尽可能巧妙地解决这个问题,这样我就可以顺利地将解决方案应用到其他应用程序中,而不是每次必须制作图表时都必须使用不同的胶带修复。

Thank you for your help!

感谢您的帮助!

回答by Jianxun Li

Can you try the following code?

你可以试试下面的代码吗?

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df.hist('ColumnName', ax=ax)
fig.savefig('example.png')