Pandas save plot to file and don't show on the screen - python

I'm making some plots of fitted data and saving them to files nicely with.
# Make the main plot.
ax = df.plot(x=df.x, y=['counts', 'fit', 'res'], title=save_file_name,
style=['b', 'g--', 'r'], xlim=xlim, ylim=ylim)
# Over plot some individual gaussians from my fit_gaussians dataframe.
for i, fit_gaus in fit_gaussians.iterrows():
plt.plot(df.x, gaussian(df.x, fit_gaus.h, fit_gaus.mu,
fit_gaus.sigma), 'y', linestyle='--')
# Save to file.
fig = ax.get_figure()
fig.savefig('test.ps')
This works great, but it also opens a window and plots to the screen. I know I can easily use matplotlib directly to recreate what I'm doing with df.plot, and just never call plt.show, but I feel like there should be some way create plot in a file with pandas with out also opening a window.

If you only don't want the pop ups you can do %matplotlib inline otherwise before you define ax just do:
plt.ioff()
Then whenever you want to actually show it you can do plt.show()

Related

plt.show() does nothing when used for the second time

I am just starting to learn data science using python on Data Camp and I noticed something while using the functions in matplotlib.pyplot
import matplotlib.pyplot as plt
year = [1500, 1600, 1700, 1800, 1900, 2000]
pop = [458, 580, 682, 1000, 1650, 6,127]
plt.plot(year, pop)
plt.show() # Here a window opens up and shows the figure for the first time
but when I try to show it again it doesn't..
plt.show() # for the second time.. nothing happens
And I have to retype the line above the show() to be able to show a figure again
Is this the normal thing or a problem?
Note: I am using the REPL
Answer
Yes, this is normal expected behavior for matplotlib figures.
Explanation
When you run plt.plot(...) you create on the one hand the lines instance of the actual plot:
>>> print( plt.plot(year, pop) )
[<matplotlib.lines.Line2D object at 0x000000000D8FDB00>]
...and on the other hand a Figure instance, which is set as the 'current figure' and accessible through plt.gcf() (short for "get current figure"):
>>> print( plt.gcf() )
Figure(432x288)
The lines (as well as other plot elements you might add) are all placed in the current figure. When plt.show() is called, the current figure is displayed and then emptied (!), which is why a second call of plt.show() doesn't plot anything.
Standard Workaround
One way of solving this is to explicitly keep hold of the current Figure instance and then show it directly with fig.show(), like this:
plt.plot(year, pop)
fig = plt.gcf() # Grabs the current figure
plt.show() # Shows plot
plt.show() # Does nothing
fig.show() # Shows plot again
fig.show() # Shows plot again...
A more commonly used alternative is to initialize the current figure explicitly in the beginning, prior to any plotting commands.
fig = plt.figure() # Initializes current figure
plt.plot(year, pop) # Adds to current figure
plt.show() # Shows plot
fig.show() # Shows plot again
This is often combined with the specification of some additional parameters for the figure, for example:
fig = plt.figure(figsize=(8,8))
For Jupyter Notebook Users
The fig.show() approach may not work in the context of Jupyter Notebooks and may instead produce the following warning and not show the plot:
C:\redacted\path\lib\site-packages\matplotlib\figure.py:459:
UserWarning: matplotlib is currently using a non-GUI backend, so
cannot show the figure
Fortunately, simply writing fig at the end of a code cell (instead of fig.show()) will push the figure to the cell's output and display it anyway. If you need to display it multiple times from within the same code cell, you can achieve the same effect using the display function:
fig = plt.figure() # Initializes current figure
plt.plot(year, pop) # Adds to current figure
plt.show() # Shows plot
plt.show() # Does nothing
from IPython.display import display
display(fig) # Shows plot again
display(fig) # Shows plot again...
Making Use of Functions
One reason for wanting to show a figure multiple times is to make a variety of different modifications each time. This can be done using the fig approach discussed above but for more extensive plot definitions it is often easier to simply wrap the base figure in a function and call it repeatedly.
Example:
def my_plot(year, pop):
plt.plot(year, pop)
plt.xlabel("year")
plt.ylabel("population")
my_plot(year, pop)
plt.show() # Shows plot
my_plot(year, pop)
plt.show() # Shows plot again
my_plot(year, pop)
plt.title("demographics plot")
plt.show() # Shows plot again, this time with title
Using command:
%matplotlib
in ipython3 help me to use separate window with plot
Start ipython3 and issue the commands:
import matplotlib.pyplot as plt
%matplotlib #plot in separate window
fig, ax = plt.subplots() #Appear empty Tcl window for image
ax.plot([1, 2, 3, 4], [5, 6, 7, 8]) #Appear graph in window
In some version of matplotlib, fig.show() does not block the window for showing plot multiple times. so, Quick fixes using self.fig.waitforbuttonpress() it waits user to press the button for next plot visualisation.
self.fig.show()
plt.pause(0.1)
self.fig.waitforbuttonpress()

Trying to add additional traces to an existing Matplotlib figure

I am using a function which spits out a figure object of validation data. My script calculates a few model parameters that I would like to plot on top of this existing figure object. How can I do this? Whenever I try to plot my modeled data, it does so in a new window. Here's what my code looks like:
datafig = plotting_function(args) #Returning a figure object
datafig.show()
plt.plot([modeled_x],[modeled_y]) #Plotting in a new window
I've tried using plt.hold() / plt.hold(True) but this doesn't do anything. Any ideas?
Edit:
MCVE:
import matplotlib.pyplot as plt
def fig_create():
fig_1, ax_1 = plt.subplots()
ax_1.plot([0,1],[0,1])
fig_2, ax_2 = plt.subplots()
ax_2.plot([0,1],[0,5])
return fig_1, ax_1, fig_2, ax_2
figure_1, axes_1, figure_2, axes_2 = fig_create()
plt.close("all") # Spyder plots even without a plt.show(), so running the function generates figures. I'm closing them here.
figure_2.show()
plt.figure(2)
plt.plot([0,1],[0,10])
Result of the MCVE: https://i.imgur.com/FiCJX33.png
You need to specify which axis to plot on. plt.figure(2) will make a figure with a number of 2, regardless of whether an existing figure has that number or not! axes_2.plot(), however will plot whatever data you input directly onto axes_2 and whatever was there already. If it doesn't immediately show up you should add plt.draw() after the plot function.
Try not to mix plt, notation and ax notation as this will create confusion later on! If you are using fig and ax, stick with those!
You can specify which figure to plot to by calling plt.figure(my_figure_index) before any plt.plot (or any other plt plotting function) call.
For example:
plt.figure(10) # creates new figure if doesn't exist yet
plt.plot(...) # plots in figure 10
plt.figure(2) # creates new figure if doesn't exist yet
plt.plot(...) # plots in this figure 2
plt.figure(10) # figure already exists, just makes it the active one
plt.plot(...) # plots in figure 10 (in addition to already existing stuff)

Python: Saving one or multiple plots in one png or pdf [duplicate]

This displays the figure in a GUI:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
But how do I instead save the figure to a file (e.g. foo.png)?
When using matplotlib.pyplot.savefig, the file format can be specified by the extension:
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
That gives a rasterized or vectorized output respectively.
In addition, there is sometimes undesirable whitespace around the image, which can be removed with:
plt.savefig('foo.png', bbox_inches='tight')
Note that if showing the plot, plt.show() should follow plt.savefig(); otherwise, the file image will be blank.
As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.
However I've found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by
forcing the the figure window to close with:
plt.close(figure_object)
(see documentation). This way I don't have a million open figures during a large loop. Example usage:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png') # save the figure to file
plt.close(fig) # close the figure window
You should be able to re-open the figure later if needed to with fig.show() (didn't test myself).
The solution is:
pylab.savefig('foo.png')
Just found this link on the MatPlotLib documentation addressing exactly this issue:
http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear
They say that the easiest way to prevent the figure from popping up is to use a non-interactive backend (eg. Agg), via matplotib.use(<backend>), eg:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
I still personally prefer using plt.close( fig ), since then you have the option to hide certain figures (during a loop), but still display figures for post-loop data processing. It is probably slower than choosing a non-interactive backend though - would be interesting if someone tested that.
UPDATE: for Spyder, you usually can't set the backend in this way (Because Spyder usually loads matplotlib early, preventing you from using matplotlib.use()).
Instead, use plt.switch_backend('Agg'), or Turn off "enable support" in the Spyder prefs and run the matplotlib.use('Agg') command yourself.
From these two hints: one, two
If you don't like the concept of the "current" figure, do:
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x*x, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
I used the following:
import matplotlib.pyplot as plt
p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05), ncol=2, fancybox=True, shadow=True)
plt.savefig('data.png')
plt.show()
plt.close()
I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png
The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:
with open('some_file.pkl', "wb") as fp:
pickle.dump(fig, fp, protocol=4)
Like this, I can later load the figure object and manipulate the settings as I please.
I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.
NB: Be careful, as sometimes this method generates huge files.
After using the plot() and other functions to create the content you want, you could use a clause like this to select between plotting to the screen or to file:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4, 5)) # size in inches
# use plot(), etc. to create your plot.
# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)
if save_file:
plt.savefig(save_file)
plt.close(fig)
else:
plt.show()
If, like me, you use Spyder IDE, you have to disable the interactive mode with :
plt.ioff()
(this command is automatically launched with the scientific startup)
If you want to enable it again, use :
plt.ion()
You can either do:
plt.show(hold=False)
plt.savefig('name.pdf')
and remember to let savefig finish before closing the GUI plot. This way you can see the image beforehand.
Alternatively, you can look at it with plt.show()
Then close the GUI and run the script again, but this time replace plt.show() with plt.savefig().
Alternatively, you can use
fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')
According to question Matplotlib (pyplot) savefig outputs blank image.
One thing should note: if you use plt.show and it should after plt.savefig, or you will give a blank image.
A detailed example:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
The Solution :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')
If you do want to display the image as well as saving the image use:
%matplotlib inline
after
import matplotlib
When using matplotlib.pyplot, you must first save your plot and then close it using these 2 lines:
fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
import matplotlib.pyplot as plt
plt.savefig("image.png")
In Jupyter Notebook you have to remove plt.show() and add plt.savefig(), together with the rest of the plt-code in one cell.
The image will still show up in your notebook.
Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:
# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'
Just a extra note because I can't comment on posts yet.
If you are using plt.savefig('myfig') or something along these lines make sure to add a plt.clf() after your image is saved. This is because savefig does not close the plot and if you add to the plot after without a plt.clf() you'll be adding to the previous plot.
You may not notice if your plots are similar as it will plot over the previous plot, but if you are in a loop saving your figures the plot will slowly become massive and make your script very slow.
Given that today (was not available when this question was made) lots of people use Jupyter Notebook as python console, there is an extremely easy way to save the plots as .png, just call the matplotlib's pylab class from Jupyter Notebook, plot the figure 'inline' jupyter cells, and then drag that figure/image to a local directory. Don't forget
%matplotlib inline in the first line!
As suggested before, you can either use:
import matplotlib.pyplot as plt
plt.savefig("myfig.png")
For saving whatever IPhython image that you are displaying. Or on a different note (looking from a different angle), if you ever get to work with open cv, or if you have open cv imported, you can go for:
import cv2
cv2.imwrite("myfig.png",image)
But this is just in case if you need to work with Open CV. Otherwise plt.savefig() should be sufficient.
well, I do recommend using wrappers to render or control the plotting. examples can be mpltex (https://github.com/liuyxpp/mpltex) or prettyplotlib (https://github.com/olgabot/prettyplotlib).
import mpltex
#mpltex.acs_decorator
def myplot():
plt.figure()
plt.plot(x,y,'b-',lable='xxx')
plt.tight_layout(pad=0.5)
plt.savefig('xxxx') # the figure format was controlled by the decorator, it can be either eps, or pdf or png....
plt.close()
I basically use this decorator a lot for publishing academic papers in various journals at American Chemical Society, American Physics Society, Opticcal Society American, Elsivier and so on.
An example can be found as following image (https://github.com/MarkMa1990/gradientDescent):
You can do it like this:
def plotAFig():
plt.figure()
plt.plot(x,y,'b-')
plt.savefig("figurename.png")
plt.close()
Nothing was working for me. The problem is that the saved imaged was very small and I could not find how the hell make it bigger.
This seems to make it bigger, but still not full screen.
https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_size_inches
fig.set_size_inches((w, h))
Hope that helps somebody.
You can save your image with any extension(png, jpg,etc.) and with the resolution you want. Here's a function to save your figure.
import os
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution)
'fig_id' is the name by which you want to save your figure. Hope it helps:)
using 'agg' due to no gui on server.
Debugging on ubuntu 21.10 with gui and VSC.
In debug, trying to both display a plot and then saving to file for web UI.
Found out that saving before showing is required, otherwise saved plot is blank. I suppose that showing will clear the plot for some reason. Do this:
plt.savefig(imagePath)
plt.show()
plt.close(fig)
Instead of this:
plt.show()
plt.savefig(imagePath)
plt.close(fig)

Keeping multiple figures open with matplotlib after script is executed

I have a question regarding windows/figures in matplotlib. I'm not sure if this is possible, but would like to know if it is.
Basically when I run my whole script, at the end a graph is plotted using matplotlib. In order to produce a new graph after running my script again I have to close that graph window.
Is there a way of keeping open the figure without closing it?
Let me give an example:
I would plot graph x by running my script.
I would then like to keep this graph on my screen, make a change to my script, plot the graph again so you may see the old graph and the new graph. Therefore n number of graphs may be visible.
Please note that I do NOT want to plot a new figure within my script. I simply would like to be able to see the graph, make a change and see the new graph WITHOUT having to save the graph.
EDIT:
This is the plotting secion of my code:
def plot_data(atb_mat_2, sd_index, sd_grad):#, rtsd):#, sd_index, sd_grad):
fig = plt.figure()
fig, (ax0, ax1, ax4, ax2, ax3) = plt.subplots(nrows=5, figsize=(15,10), num='Current Relative Method'+' ' + path)
ax0.plot(atb_mat_2)
ax0.set_title('Relative Track',fontsize=11)
ax0.set_ylim([-10,10])
if len(sd_index)!=0:
if len(sd_index)>1:
for i in range(1, len(sd_index)):
if sd_grad[i]==1:
ax0.axvspan(sd_index[i-1],sd_index[i], edgecolor='r', lw=None, alpha=0.1)
ax1.plot(rtsd)
ax1.set_title('RT Standard Deviation',fontsize=11)
ax1.set_ylim([0,250])
ax4.plot(abs_track_data)
ax4.set_title('Absolute Track',fontsize=11)
ax4.set_ylim([3000,5000])
ax2.plot(splitpo)
ax2.set_title('Track Split',fontsize=11)
ax2.set_ylim([0,20])
ax3.plot(ts)
ax3.set_title('TS Standard Deviation',fontsize=11)
ax3.set_ylim([0,100])
fig.tight_layout()
plt.show()
Thanks alot of any advice and sorry if this answer is obvious as I'm fairly new.
You can do it using ipython.
Write your script and save it as (for example) test.py. The script should create a figure, do the plotting and show the plot:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.linspace(-1, 1, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Start the ipython console using:
ipython --pylab=qt
Or whatever backend you want to use.
In the ipython shell type:
%run /path/to/the/test.py
This will create a figure, and show the plot.
After that change your script. For example change the 5th line to:
x = np.linspace(-0, 2, 100)
Repeat the %run command in the ipython shell:
%run /path/to/the/test.py
Another figure will pop up with the new plot. Old figure will be also visible (this won't remove it or replace it).

Save plot to image file instead of displaying it using Matplotlib

This displays the figure in a GUI:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
But how do I instead save the figure to a file (e.g. foo.png)?
When using matplotlib.pyplot.savefig, the file format can be specified by the extension:
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
That gives a rasterized or vectorized output respectively.
In addition, there is sometimes undesirable whitespace around the image, which can be removed with:
plt.savefig('foo.png', bbox_inches='tight')
Note that if showing the plot, plt.show() should follow plt.savefig(); otherwise, the file image will be blank.
As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.
However I've found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by
forcing the the figure window to close with:
plt.close(figure_object)
(see documentation). This way I don't have a million open figures during a large loop. Example usage:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png') # save the figure to file
plt.close(fig) # close the figure window
You should be able to re-open the figure later if needed to with fig.show() (didn't test myself).
The solution is:
pylab.savefig('foo.png')
Just found this link on the MatPlotLib documentation addressing exactly this issue:
http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear
They say that the easiest way to prevent the figure from popping up is to use a non-interactive backend (eg. Agg), via matplotib.use(<backend>), eg:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
I still personally prefer using plt.close( fig ), since then you have the option to hide certain figures (during a loop), but still display figures for post-loop data processing. It is probably slower than choosing a non-interactive backend though - would be interesting if someone tested that.
UPDATE: for Spyder, you usually can't set the backend in this way (Because Spyder usually loads matplotlib early, preventing you from using matplotlib.use()).
Instead, use plt.switch_backend('Agg'), or Turn off "enable support" in the Spyder prefs and run the matplotlib.use('Agg') command yourself.
From these two hints: one, two
If you don't like the concept of the "current" figure, do:
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x*x, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
I used the following:
import matplotlib.pyplot as plt
p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05), ncol=2, fancybox=True, shadow=True)
plt.savefig('data.png')
plt.show()
plt.close()
I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png
The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:
with open('some_file.pkl', "wb") as fp:
pickle.dump(fig, fp, protocol=4)
Like this, I can later load the figure object and manipulate the settings as I please.
I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.
NB: Be careful, as sometimes this method generates huge files.
After using the plot() and other functions to create the content you want, you could use a clause like this to select between plotting to the screen or to file:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4, 5)) # size in inches
# use plot(), etc. to create your plot.
# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)
if save_file:
plt.savefig(save_file)
plt.close(fig)
else:
plt.show()
If, like me, you use Spyder IDE, you have to disable the interactive mode with :
plt.ioff()
(this command is automatically launched with the scientific startup)
If you want to enable it again, use :
plt.ion()
You can either do:
plt.show(hold=False)
plt.savefig('name.pdf')
and remember to let savefig finish before closing the GUI plot. This way you can see the image beforehand.
Alternatively, you can look at it with plt.show()
Then close the GUI and run the script again, but this time replace plt.show() with plt.savefig().
Alternatively, you can use
fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')
According to question Matplotlib (pyplot) savefig outputs blank image.
One thing should note: if you use plt.show and it should after plt.savefig, or you will give a blank image.
A detailed example:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
The Solution :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')
If you do want to display the image as well as saving the image use:
%matplotlib inline
after
import matplotlib
When using matplotlib.pyplot, you must first save your plot and then close it using these 2 lines:
fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
import matplotlib.pyplot as plt
plt.savefig("image.png")
In Jupyter Notebook you have to remove plt.show() and add plt.savefig(), together with the rest of the plt-code in one cell.
The image will still show up in your notebook.
Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:
# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'
Just a extra note because I can't comment on posts yet.
If you are using plt.savefig('myfig') or something along these lines make sure to add a plt.clf() after your image is saved. This is because savefig does not close the plot and if you add to the plot after without a plt.clf() you'll be adding to the previous plot.
You may not notice if your plots are similar as it will plot over the previous plot, but if you are in a loop saving your figures the plot will slowly become massive and make your script very slow.
Given that today (was not available when this question was made) lots of people use Jupyter Notebook as python console, there is an extremely easy way to save the plots as .png, just call the matplotlib's pylab class from Jupyter Notebook, plot the figure 'inline' jupyter cells, and then drag that figure/image to a local directory. Don't forget
%matplotlib inline in the first line!
As suggested before, you can either use:
import matplotlib.pyplot as plt
plt.savefig("myfig.png")
For saving whatever IPhython image that you are displaying. Or on a different note (looking from a different angle), if you ever get to work with open cv, or if you have open cv imported, you can go for:
import cv2
cv2.imwrite("myfig.png",image)
But this is just in case if you need to work with Open CV. Otherwise plt.savefig() should be sufficient.
well, I do recommend using wrappers to render or control the plotting. examples can be mpltex (https://github.com/liuyxpp/mpltex) or prettyplotlib (https://github.com/olgabot/prettyplotlib).
import mpltex
#mpltex.acs_decorator
def myplot():
plt.figure()
plt.plot(x,y,'b-',lable='xxx')
plt.tight_layout(pad=0.5)
plt.savefig('xxxx') # the figure format was controlled by the decorator, it can be either eps, or pdf or png....
plt.close()
I basically use this decorator a lot for publishing academic papers in various journals at American Chemical Society, American Physics Society, Opticcal Society American, Elsivier and so on.
An example can be found as following image (https://github.com/MarkMa1990/gradientDescent):
You can do it like this:
def plotAFig():
plt.figure()
plt.plot(x,y,'b-')
plt.savefig("figurename.png")
plt.close()
Nothing was working for me. The problem is that the saved imaged was very small and I could not find how the hell make it bigger.
This seems to make it bigger, but still not full screen.
https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_size_inches
fig.set_size_inches((w, h))
Hope that helps somebody.
You can save your image with any extension(png, jpg,etc.) and with the resolution you want. Here's a function to save your figure.
import os
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution)
'fig_id' is the name by which you want to save your figure. Hope it helps:)
using 'agg' due to no gui on server.
Debugging on ubuntu 21.10 with gui and VSC.
In debug, trying to both display a plot and then saving to file for web UI.
Found out that saving before showing is required, otherwise saved plot is blank. I suppose that showing will clear the plot for some reason. Do this:
plt.savefig(imagePath)
plt.show()
plt.close(fig)
Instead of this:
plt.show()
plt.savefig(imagePath)
plt.close(fig)

Categories

Resources