qshahryar
qshahryar

Reputation: 63

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.

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

Upvotes: 0

Views: 456

Answers (2)

ALollz
ALollz

Reputation: 59549

Use matplotlib to create a figure and axis objects, then tell pandas which axes to plot on using the ax argument. Finally, use matplotlib (or the fig) to save the figure.

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

enter image description here

Upvotes: 2

Instead of using *.hist() I would use 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')

Upvotes: 0

Related Questions