使用 matplotlib 将两个不同的图形保存在不同的文件中

Saving two different figures on different files with matplotlib

这可能很明显,但我做不到。我是 Python 的新手,最近才开始使用 matplotlib,所以我看不出问题所在。

我正在做以下事情:

我得到的是两个具有相同图形的png文件:DataFrame直方图。 (我记得在MATLAB上有类似的问题,我花了一些时间才找到方法)

代码如下:

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Suppose 'housing' is a pandas.DataFrama with shape (20640, 11)

# Make a histogram of each column of housing data frame
housing.hist(bins=50, figsize=(20, 15))

# Save histogram as a file
os.makedirs('im', exist_ok=True)
plt.savefig('im/housing_hist.png')

# Create a new attribute which represent income category
housing["income_cat"] = pd.cut(housing["median_income"],
                               bins=[0., 1.5, 3.0, 4.5, 6., np.inf],
                               labels=[1, 2, 3, 4, 5])

# Create a histogram of income_cat
housing["income_cat"].hist()
plt.savefig('im/income_cat_hist.png')

我需要帮助来保存不同的文件。

感谢您的宝贵时间。

从图形对象中保存图形更可靠。在 Python(以及更新版本的 MATLAB)中,图形是一种特定的数据类型。 pandas hist 函数 returns 轴或轴数组。

如果您制作的是单轴,您可以使用 figure 属性 获取图形,然后从中调用 savefig

所以像这样的东西应该有用。

ax1 = housing.hist(bins=50, figsize=(20, 15))
ax1.figure.savefig('im/housing_hist.png')

如果你正在制作多个轴,你会得到一个 numpy 数组轴,你可以将其展平并获取第一个元素:

axs1 = housing.hist(bins=50, figsize=(20, 15))
axs1.ravel()[0].figure.savefig('im/housing_hist.png')

编辑:为了清楚起见,对于第二个数字你应该这样做:

ax2 = housing["income_cat"].hist()
ax2.figure.savefig('im/income_cat_hist.png')

嗯,我认为解决方案是在每个 plt.savefig('...') 之后添加一个 plt.clf()。我看到这个 post 得到它:

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

我希望得到比我更好的答案。