I plot figures a lot during my python (through Spyder env.) usage. However, when I try to use plt.savefig('figure.png'), the saved figure has a different size from the inline figure plotted on Spyder.
For ex., when I use this command:
plt.savefig('fig1.png')
The saved figure looks like this:
Note that there's something weird with the saved figure, e.g.: the title is cropped, the size is not proportional.
However, the following is the inline figure:
I tried to modify the size through matplotlib.pyplot documentation but couldn't find such setting. Does anyone know how to save the figure with the exact setting as the inline plot?
The inline figure size plotted in Spyder (or any other IDE or editor) depends on how the editor handles showing figures.
If you want to have an exact size as output of your code, use figsize before plotting code. (It uses inches)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
# Code to produce figure
You can also determine DPI when creating figure or saving.
plt.figure(figsize=(10, 10), dpi=300)
# or
plt.savefig(file_path, dpi=300)
Related
I have the following image (of dimensions 1151x781)
If I try to plot this image with matplotlib as follows
import matplotlib.pyplot as plt
img = plt.imread("this_image.png")
plt.figure(figsize=(10, 7))
plt.imshow(img, cmap="gray")
The result is the following
This happens if I execute this code by opening a Python shell from the terminal or in a jupyter notebook. The addition of the line matplotlib.use('TkAgg') before plotting does not seem to help.
I am on macOS Catalina (10.15.4) and I tried this with Python 3.7.1 and Matplotlib 3.0.2.
Do you also experience the same thing? What's the solution?
Please, do not tell me that the solution is to change the size of the figure! Because I know that, by changing the size of the figure, this problem can go away or new black lines are visualized. Of course, I don't want to lose time trying different sizes in order to understand which ones work out and, clearly, this solution is impractical and inflexible.
Change dpi of figure:
img = plt.imread('this_image.png')
plt.figure(figsize=(10,7), dpi=300)
plt.imshow(img, cmap='gray')
Output:
It seems that the figsize option only changes the ratio of the height to width. Atleast this is the case when using jupyter notebooks. Here is an example:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
plt.figure(figsize=(16,8))
plt.plot(np.arange(1,10),np.arange(1,10))
plt.show()
plt.figure(figsize=(24,6))
plt.plot(np.arange(1,10),np.arange(1,10))
plt.show()
I was hoping that figsize intended inches, not a relative ratio. How would you go about enforcing that in python/ jupyter notebooks.
If you use a large figsize, say figsize=(50, 5) you will notice that the lines, the labels, everything is incredibly thin and small with respect to a plot with normal size.
This happens because you are using widths that are not compatible with the width of the output cell
and the notebook just scales down the figure to make it fit in the output cell.
To have the behavior you asked for, you need a horizontal scrolling capability in the output cell. I don't know of a `nbextension` that can enable horizontal scrolling in output cells.
After a bit of experimenting, it looks like using the nbagg backend
%matplotlib nbagg
gives you a scrollable output cell, and an interactive one as well, inside the notebook and possibly it is what you want.
Addendum
I've found this issue on IPython's github, with a request for horizontal scrolling in output cell — as you can see it's dated 2012 and there is no followup of sort.
plt.gcf().set_size_inches(16, 8)
After change figsize the figure size do changed when the parameter in a certain range.In my condition,size not growing after size above (24,8).When it's still below the range the size do increase.It's base on your displayer dpi, you can set the dpi in figure but eventually it's rely on your hardware.
The figaspect is set by matplotlib.figure.figaspect
If you save figures to files use savefig,you will see the image size increase also.
I have plotted a graph with 14 subplots in matplotlib. In the window the plot looks like this-
I save this plot using following command-
import matplotlib.pyplot as plt
plt.savefig('img.png')
But the image that is saved looked like this-
Notice that the x axis labels get overlapped because the image is shrinked. The savefig() function has optional argument dpi, but it changes the resolution/quality of saved plot.
I also tried this, but it is used to improve image resolution.
I want the axis labels to be nicely spaced as in the window. Thanks
Ok, So I found the solution myself and posting it here for anyone who might face similar problem. I changed the figure size before saving and following code does the trick-
import matplotlib.pyplot as plt
fig =plt.gcf()
fig.set_size_inches(20, 11,dpi=100)
plt.savefig('img.png')
I cannot get matshow() or imshow() to actually display the plot when both of the following conditions are true: (1) interactive mode is on: import matplotlib.pyplot as plot; plot.ion(), and (2) I am trying to use matshow on a specific subplot: fig = plot.figure(); ax = fig.add_subplot(111); ax.matshow([[1,2],[3,0]]).
Using plot.matshow([[1,2],[3,0]]) (note: no explicit axes) works find in interactive mode, but will always create a new figure window with a single axes object. The above code with the subplot also works fine without interactive mode using plot.show(), and will put the image on the correct axes.
More oddly, the above code with the subplot will show the image if I interact with the figure, such as by using the zoom tool and clicking randomly in the figure window (there is no visible axes object, but I just click somewhere in the middle of the figure window).
Any ideas what might be causing this, how I could fix it, or how I could get around it to use matshow or imshow on a specified subplot (the end use case is to have more than 1 subplot in the figure)? This occurs in python (2.7.6) and ipython (1.1.1)
This may have something to do with this documentation:
Display an array as a matrix in a new figure window.
However, you may as well use imshow with suitable arguments:
import matplotlib.pyplot as plt
plt.imshow(mat, interpolation='nearest', origin='upper', aspect='equal')
This should do the same thing while being a bit less odd. This is actually exactly what matshow does internally. It just adds a few tick markers to the image.
Also, by having a look at the source (or closely reading the help string), you may try to do:
plt.matshow(mat, fignum=0)
This should force it use current axis, which it picks by using gca.
In addition to this, there is ax.matshow which you used, as well. Actually plt.matshow is a very thin wrapper around ax.matshow, mostly to create the new image.
If you still have problems with matshow or imshow in subplots, please make a minimal complete example for us to try! Here is something I tried in the interactive shell (IPython):
figure()
ax = subplot(121)
ax2 = subplot(122)
ax.matshow(random.random((20,30)))
ax2.plot(linspace(-1,1,100), linspace(-1,1,100)**2)
draw()
(Could the problem be a missing draw?)
What I got:
When using Matplotlib to generate figures with hatching (e.g. pie, bar, bubble charts), I'm having some trouble getting decent resolution out of the PDF version of the figure. Saving as EPS is fine, but as soon as I use epstopdf or MPL's savefig(*.pdf), the hatching becomes pixellated and distored... the vector nature of the image appears to have been lost.
See minimal code below.
from matplotlib import pyplot as plt
# Define hatching styles
hatching = ["/", "o"]
fig, ax = plt.subplots()
wedges, texts = ax.pie([0.4, 0.6], colors=("SteelBlue", "Tomato"))
# Apply the hatching
for j, patch in enumerate(wedges): patch.set_hatch(hatching[j])
fig.savefig("hatchtest.pdf")
I've used Gimp to zoom in on a part of the plot to illustrate the difference...
Zoomed in on the EPS figure
Zoomed in on the PDF figure
As for system specific details, I'm using Ubuntu 13.04, Python 2.7.4 with MPL 1.2.1. I've tried different backends but nothing seems to resolve this. I'd ideally like to have nice vector images in EPS and PDF so that it's all journal-friendly. Any pointers would be much appreciated.
Just a problem with Evince PDF viewer. Viewing in Adobe Reader or printing the plot gives the desired result.