Change figsize in matplotlib - python

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.

Related

Python - save a figure with the same size and setting

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)

Jupyter: Seaborn pairplot difficult to set graph dimensions for?

I was trying to create a bivariate scatterplot of each variable against every other that are in a dataframe, and I found sns.pairplot() was exactly what I needed.
However, no matter what I do (and I have tried all of the advice found in this question), the plots keep coming out too spread out, as well as in general too big. In the picture below, only the first two rows and four columns out of 12 variables display on my entire screen.
I have found out that my use of
%config InlineBackend.figure_format = 'svg'
to create non-blurry graphs on my high-ppi screen is partially at blame, as without it, I instead get this graph, which fits perfectly on my screen, but is now too small and I would prefer to scroll slightly around while having a bigger pic.
(note: the additional options below have no effect)
How can I make the grid of plots customizable in its overall size as well as spacing? As it stands, no options work, and one graphics backend (the default one) produces too small graphs, while the 'svg' backend produces too large ones.
EDIT: Editing sns.set(rc={'figure.figsize':(x,y)}) or the height/ aspect options improve nothing: the former produces no change, while the latter two change how big the individual plots are (with height=1 making them indecipherable), but the overall "grid" is still as bulky and overly large as before.
Essentially you are asking how to display the figure in its original size in a jupyter notebook.
That translates into how to add scrollbars if it exceeds the room it's given by the layout of the output cell.
I think for the horizontal direction this can be done as follows. However for the vertical direction this does not seem to work.
%matplotlib inline
# Cell2
from IPython.display import display, HTML
CSS = """div.output_area img {max-width:None !important;max-height: None !important";}"""
display(HTML('<style>{}</style>'.format(CSS)))
# Cell3
import matplotlib.pyplot as plt
fig, ax = plt.subplots(ncols=8, figsize=(20,10))

Python Pandas plot command produces small images on high resolution display

I am using the following line of code in my python application.
df['Close'].plot()
The figure produced by this code is very small on my high resolution display (Microsoft Surface Studio). I have looked at the documentation for the pandas plot command and matplotlib but have not found any relevant settings. Any help appreciated.
I would guess that you want to leave the figure size constant but change the dpi (dots per inch).
Somewhere on top of your script or notebook add
import matplotlib.pyplot as plt
plt.rcParams["figure.dpi"] = 144
Change 144 to your liking. (Note that multiples of 72 usually give nice lines).
The figsize parameter is what you're after.
df['Close'].plot(figsize=(20,10))
If you are in a Jupyter Notebook, there may be an issue where the notebook shrinks figures to fit in the cell output as .plot(figsize=x,y) increases the size. You will notice the text getting smaller but the plot seems to stay the same size, as you increase the figsize parameters.

How to prevent Matplotlib from clipping away my axis labels?

I'm preparing some plots for a scientific paper, which need to be wide and short in order to fit into the page limit. However, when I save them as pdf, the x axis labels are missing, because (I think) they're outside the bounding box.
Putting the following into an iPython notebook reproduces the problem.
%pylab inline
pylab.rcParams['figure.figsize'] = (8.0, 2.0)
plot([1,5,2,4,6,2,1])
xlabel("$x$")
ylabel("$y$")
savefig("test.pdf")
The resulting pdf file looks like this:
How can I change the bounding box of the pdf file? Ideally I'd like a solution that "does it properly", i.e. automatically adjusts the size so that everything fits neatly, including getting rid of that unnecessary space to the left and right - but I'm in a hurry, so I'll settle for any way to change the bounding box, and I'll guess numbers until it looks right if I have to.
After a spot of Googling, I found an answer: you can give bbox_inches='tight' to the savefig command and it will automatically adjust the bounding box to the size of the contents:
%pylab inline
pylab.rcParams['figure.figsize'] = (8.0, 2.0)
plot([1,5,2,4,6,2,1])
xlabel("$x$")
ylabel("$y$")
savefig("test.pdf",bbox_inches='tight')
Those are some tight inches, I guess.
Note that this is slightly different from Ffisegydd's answer, since it adjusts the bounding box to the plot, rather than changing the plot to fit the bounding box. (But both are fine for my purposes.)
You can use plt.tight_layout() to have matplotlib adjust the layout of your plot. tight_layout() will automatically adjust the dimensions, and can also be used when you have (for example) overlapping labels/ticks/etc.
%pylab inline
pylab.rcParams['figure.figsize'] = (8.0, 2.0)
plot([1,5,2,4,6,2,1])
xlabel("$x$")
ylabel("$y$")
tight_layout()
savefig("test.pdf")
Here is a .png of the output (can't upload pdfs to SO but I've checked it and it works the same way for a pdf).
If you are preparing the plot for a scientific paper, I suggest to do the 'clipping' by yourself,
using
plt.subplots_adjust(left,right,bottom,top,..)
after the creation of the figure and before saving it. If you are running from an ipython console you can also call subplots_adjust after the generation of the figure, and tune the margins by trial and error. Some backends (I think at least the Qt backend) also expose a GUI for this feature.
Doing this by hand takes time, but most times provides a more precise result, especially with Latex rendering in my experience.
This is the only option whenever you have to stack vertically or horizontally two figures (with a package like subfigure for example), as tight_layout will not guarantee the same margins in the two figures, and the axis will result misaligned in the paper.
This is a nice link on using matplotlib for publications, covering for example how to set the figure width to match the journal column width.

Saving images in Python at a very high quality

How can I save Python plots at very high quality?
That is, when I keep zooming in on the object saved in a PDF file, why isn't there any blurring?
Also, what would be the best mode to save it in?
png, eps? Or some other? I can't do pdf, because there is a hidden number that happens that mess with Latexmk compilation.
If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:
plt.savefig('destination_path.eps', format='eps')
I have found that EPS files work best and the dpi parameter is what really makes them look good in a document.
To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax):
ax.view_init(elev=elevation_angle, azim=azimuthal_angle)
Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis).
I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.
Just to add my results, also using Matplotlib.
.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)
I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.
Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".
You can save to a figure that is 1920x1080 (or 1080p) using:
fig = plt.figure(figsize=(19.20,10.80))
You can also go much higher or lower. The above solutions work well for printing, but these days you want the created image to go into a PNG/JPG or appear in a wide screen format.
Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:
beingsaved = plt.figure()
# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)
beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)
In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:
Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:
import seaborn as sb
image = sb.heatmap(matrix) # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png") # This saves it
This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.
Another way I like is this. I set the size of the next image as follows:
plt.subplots(figsize=(15,15))
And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

Categories

Resources