如何使用 Pandas 创建特定的图,然后将它们存储为 PNG 文件?

How to create specific plots using Pandas and then store them as PNG files?

所以我尝试为数据集中的每个特定变量创建直方图,然后将其保存为 PNG 文件。

我的代码如下:

import pandas as pd
import matplotlib.pyplot as plt 
x=combined_databook.groupby('x_1').hist()
x.figure.savefig("x.png")

我不断收到“AttributeError:'Series' 对象没有属性 'figure'”

而不是使用 *.hist() 我会使用 matplotlib.pyplot.hist().

示例:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

y =[10, 20,30,40,100,200,300,400,1000,2000]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = Values')
plt.title('my plot')
ax.legend()
plt.show()

fig.savefig('tada.png')

使用 matplotlib 创建一个图形和轴对象,然后使用 ax 参数告诉 pandas 要在哪个轴上绘制。最后用matplotlib(或者fig)保存图。

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

# Sample Data (3 groups, normally distributed)
df = pd.DataFrame({'gp': np.random.choice(list('abc'), 1000),
                   'data': np.random.normal(0, 1, 1000)})

fig, ax = plt.subplots()
df.groupby('gp').hist(ax=ax, ec='k', grid=False, bins=20, alpha=0.5)
fig.savefig('your_fig.png', dpi=200)

your_fig.png