I'm using matplotlib.pyplot in interactive mode. I want to check that I've formatted the figure correctly using plt.show(), but every time I do the figure is cleared and I have to plot it again. I'd like to be able to view the plot in interactive mode without the figure clearing.
What happens:
>>> plt.plot(np.arange(5))
>>> plt.show()
<figure-displays>
>>> plt.show()
<nothing-happens>
>>> plt.savefig('my_figure.png')
<empty-file-is-saved>
What I want:
>>> plt.plot(np.arange(5))
>>> plt.show()
<figure-displays>
>>> plt.show()
<figure-displays>
>>> plt.savefig('my_figure.png')
<figure-is-saved>
If what you want is to be able to see the changes every time, you can save multiple files, and as long as you don't call plt.close(), the plots will just keep adding.
import matplotlib.pyplot as plt
plt.plot([5,1,4],[3,2,1])
plt.savefig('1.png')
plt.plot([3,2,1],[1,2,3])
plt.savefig('2.png')
There might be many files, so it is best to do this in a New folder. If you are programming with the python shell only, this is what you can do to change directories:
>>> import os
>>> path = 'C:\\Users\\Caitlin\\Desktop\\New folder'
>>> os.chdir(path)
>>>
If you are using a python file, simply place the file into the New folder. Or, you can simply add the path into savefig():
plt.savefig('C:\\Users\\Caitlin\\Desktop\\New folder\\1.png')
Related
I'm new to python and programing and I'm trying to make a code to display an image with some data from a .fits file. I'm first trying to make this example I found from this site: https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py. When I run it, it shows everything it should, except the figure, which is the most important part. How do I make the figure show up?
The code is the following:
import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
from astropy.utils.data import get_pkg_data_filename
from astropy.io import fits
image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
fits.info(image_file)
image_data = fits.getdata(image_file, ext=0)
print(image_data.shape)
plt.figure()
plt.imshow(image_data, cmap='gray')
plt.colorbar()
Appending plt.show() at the end of your code should work ...
I ignored the fact that the figure was not showing up in the example and went straight to my .fits file. With that file the figure worked fine. Turns out there was probably something wrong with the example file.
Here's a dummy script that makes three plots and saves them to PDF.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
I'm using spyder, which uses IPython. When I run this script, three windows pop at me and then go away. It works, but it's a little annoying.
How can I make the figures get saved to pdf without ever being rendered on my screen?
I'm looking for something like R's
pdf("path/to/plot/name.pdf")
commands
dev.off()
inasmuch as nothing gets rendered on the screen, but the pdf gets saved.
Aha. Partially based on the duplicate suggestion (which wasn't exactly a duplicate), this works:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
import matplotlib
old_backend = matplotlib.get_backend()
matplotlib.use("pdf")
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
matplotlib.use(old_backend)
Basically, set the backend to something like a pdf device, and then set it back to whatever you're accustomed to.
I am referring you to this StackOverflow answer which cites this article as an answer. In the SO answer they also suggest plt.ioff() but are concerned that it could disable other functionality should you want it.
In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
plt.savefig(filename1 + '.pdf')
or
plt.savefig(filename1 + '.jpg')
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?
Use PdfPages to solve your problem. Pass your figure object to the savefig method.
For example, if you have a whole pile of figure objects open and you want to save them into a multi-page PDF, you might do:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
pdf.savefig( fig )
pdf.close()
Do you mean save multiple figures into one file, or save multiple figures using one script?
Here's how you can save two different figures using one script.
>>> from matplotlib import pyplot as plt
>>> fig1 = plt.figure()
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x10261bd90>]
>>> fig2 = plt.figure()
>>> plt.plot(range(10,20))
[<matplotlib.lines.Line2D object at 0x10263b890>]
>>> fig1.savefig('fig1.png')
>>> fig2.savefig('fig2.png')
...which produces these two plots into their own ".png" files:
To save them to the same file, use subplots:
>>> from matplotlib import pyplot as plt
>>> fig = plt.figure()
>>> axis1 = fig.add_subplot(211)
>>> axis1.plot(range(10))
>>> axis2 = fig.add_subplot(212)
>>> axis2.plot(range(10,20))
>>> fig.savefig('multipleplots.png')
The above script produces this single ".png" file:
I struggled with the same issue. I was trying to put 2,000 scatter plots into a single .pdf. I was able to start the procedure, but it aborted after a few hundred.
Even when I created six scatter charts into one .pdf, the .pdf file was enormous (like 7mb) for just six .jpg's that were 30kb each. When I opened the .pdf, it appeared that the .pdf was painting every point on the chart (each chart had thousands of points) instead of displaying an image. Some day, I will figure out the correct options, but here is a quick and dirty work-around. I printed the scatter plots to individual .jpg files in a local directory.
I'm using python 2.7 on Ubuntu to draw charts from text files containing data.
My point is, when using python executables in shell, I have no problem recording plots, but if I want them shown on my screen instead I have to go through the graphic interface. If possible, I would very much like to skip that part and get a dynamic display that I can interact with (as if I were to run my script from a python shell)!!
a MWE of what i'm doing is :
MWE
import numpy as np
import matplotlib.pyplot as plt
with open('filename','r') as myfile:
DATA = np.genfromtxt(myfile,unpack=True)
fig = plt.figure()
... my plot configuration ...
plt.savefig("image_name"+'.png')
plt.close()
end of MWE
Using this script image_name.png appears in my repertory. I tried replacing the last 2 lines with plt.plot() and plt.draw() but nothing happened.
Many thanks!
Michel
(edited)
In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
plt.savefig(filename1 + '.pdf')
or
plt.savefig(filename1 + '.jpg')
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?
Use PdfPages to solve your problem. Pass your figure object to the savefig method.
For example, if you have a whole pile of figure objects open and you want to save them into a multi-page PDF, you might do:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
pdf.savefig( fig )
pdf.close()
Do you mean save multiple figures into one file, or save multiple figures using one script?
Here's how you can save two different figures using one script.
>>> from matplotlib import pyplot as plt
>>> fig1 = plt.figure()
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x10261bd90>]
>>> fig2 = plt.figure()
>>> plt.plot(range(10,20))
[<matplotlib.lines.Line2D object at 0x10263b890>]
>>> fig1.savefig('fig1.png')
>>> fig2.savefig('fig2.png')
...which produces these two plots into their own ".png" files:
To save them to the same file, use subplots:
>>> from matplotlib import pyplot as plt
>>> fig = plt.figure()
>>> axis1 = fig.add_subplot(211)
>>> axis1.plot(range(10))
>>> axis2 = fig.add_subplot(212)
>>> axis2.plot(range(10,20))
>>> fig.savefig('multipleplots.png')
The above script produces this single ".png" file:
I struggled with the same issue. I was trying to put 2,000 scatter plots into a single .pdf. I was able to start the procedure, but it aborted after a few hundred.
Even when I created six scatter charts into one .pdf, the .pdf file was enormous (like 7mb) for just six .jpg's that were 30kb each. When I opened the .pdf, it appeared that the .pdf was painting every point on the chart (each chart had thousands of points) instead of displaying an image. Some day, I will figure out the correct options, but here is a quick and dirty work-around. I printed the scatter plots to individual .jpg files in a local directory.