11

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

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

14 Comments

@ atru: Yes, I am using matplotlib. I tried the way you suggested but it saves an empty png file.
Can you share more of your code then? It works perfect for me. In fact I was pretty happy with the quality.
@ atru: I have edited the code in the question section with savefig. Please take a look. Thank you
Briefly scrolling through this post and checking it out - do you have a pl.show() before pl.savefig() ?
I just realized this too. I have pl.show() before pl.savefig(). I switched those lines of code and now it works fine. Thank you very much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.