Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save histogram plot in python?

I have following code that generates a histogram. How can I save the histogram automatically using the code? I tried what we do for other plot types but that did not work for histogram.a is a 'numpy.ndarray'.

a = [-0.86906864 -0.72122614 -0.18074998 -0.57190212 -0.25689268 -1.
     0.68713553  0.29597819  0.45022949  0.37550592  0.86906864  0.17437203
     0.48704826  0.2235648   0.72122614  0.14387731  0.94194514 ]

fig = pl.hist(a,normed=0)
pl.title('Mean')
pl.xlabel("value")
pl.ylabel("Frequency")
pl.savefig("abc.png")
like image 766
A.S Avatar asked Sep 25 '17 18:09

A.S


1 Answers

This works for me:

import matplotlib.pyplot as pl
import numpy as np

a = np.array([-0.86906864, -0.72122614, -0.18074998, -0.57190212, -0.25689268 ,-1. ,0.68713553 ,0.29597819, 0.45022949, 0.37550592, 0.86906864, 0.17437203, 0.48704826, 0.2235648, 0.72122614, 0.14387731, 0.94194514])

fig = pl.hist(a,normed=0)
pl.title('Mean')
pl.xlabel("value")
pl.ylabel("Frequency")
pl.savefig("abc.png")

a in the OP is not a numpy array and its format also needs to be modified (it needs commas, not spaces as delimiters). This program successfully saves the histogram in the working directory. If it still does not work, supply it with a full path to the location where you want to save it like this

pl.savefig("/Users/atru/abc.png")

The pl.show() statement should not be placed before savefig() as it creates a new figure which makes savefig() save a blank figure instead of the desired one as explained in this post.

like image 170
atru Avatar answered Nov 16 '22 17:11

atru