简体   繁体   English

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

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

So I am trying to create histograms for each specific variable in my dataset and then save it as a PNG file.所以我试图为我的数据集中的每个特定变量创建直方图,然后将其保存为 PNG 文件。

My code is as follows:我的代码如下:

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

I keep getting "AttributeError: 'Series' object has no attribute 'figure'"我不断收到“AttributeError: 'Series' object 没有属性 'figure'”

Use matplotlib to create a figure and axis objects, then tell pandas which axes to plot on using the ax argument.使用matplotlib创建图形和轴对象,然后使用ax参数告诉pandas哪个轴到 plot。 Finally, use matplotlib (or the fig) to save the figure.最后,使用matplotlib (或图)保存图。

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你的无花果.png

在此处输入图像描述

Instead of using *.hist() I would use matplotlib.pyplot.hist() .而不是使用*.hist()我会使用matplotlib.pyplot.hist()

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM