Comparison of different approaches to set exact image sizes in pixels
This answer will focus on:
savefig
: how to save to a file, not just show on screen- setting the size in pixels
Here is a quick comparison of some of the approaches I’ve tried with images showing what the give.
Summary of current status: things are messy, and I am not sure if it is a fundamental limitation, or if the use case just didn’t get enough attention from developers. I couldn’t easily find an upstream discussion about this.
Baseline example without trying to set the image dimensions
Just to have a comparison point:
base.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')
Run:
./base.py
identify base.png
Outputs:
fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
My best approach so far: plt.savefig(dpi=h/fig.get_size_inches()[1]
height-only control
I think this is what I’ll go with most of the time, as it is simple and scales:
get_size.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size.png',
format='png',
dpi=height/fig.get_size_inches()[1]
)
Run:
./get_size.py 431
Outputs:
get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
and
./get_size.py 1293
Outputs:
main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
I tend to set just the height because I’m usually most concerned about how much vertical space the image is going to take up in the middle of my text.
plt.savefig(bbox_inches='tight'
changes image size
I always feel that there is too much white space around images, and tended to add bbox_inches='tight'
from:
Removing white space around a saved image
However, that works by cropping the image, and you won’t get the desired sizes with it.
Instead, this other approach proposed in the same question seems to work well:
plt.tight_layout(pad=1)
plt.savefig(...
which gives the exact desired height for height equals 431:
Fixed height, set_aspect
, automatically sized width and small margins
Ermmm, set_aspect
messes things up again and prevents plt.tight_layout
from actually removing the margins… this is an important use case that I don’t have a great solution for yet.
Asked at: How to obtain a fixed height in pixels, fixed data x/y aspect ratio and automatically remove remove horizontal whitespace margin in Matplotlib?
plt.savefig(dpi=h/fig.get_size_inches()[1]
+ width control
If you really need a specific width in addition to height, this seems to work OK:
width.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'width.png',
format='png',
dpi=h/hi
)
Run:
./width.py 431 869
Output:
width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000
and for a small width:
./width.py 431 869
Output:
width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000
So it does seem that fonts are scaling correctly, we just get some trouble for very small widths with labels getting cut off, e.g. the 100
on the top left.
I managed to work around those with Removing white space around a saved image
plt.tight_layout(pad=1)
which gives:
width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000
From this, we also see that tight_layout
removes a lot of the empty space at the top of the image, so I just generally always use it.
Fixed magic base height, dpi
on fig.set_size_inches
and plt.savefig(dpi=
scaling
I believe that this is equivalent to the approach mentioned at: https://stackoverflow.com/a/13714720/895245
magic.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'magic.png',
format='png',
dpi=h/magic_height*dpi,
)
Run:
./magic.py 431 231
Outputs:
magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
And to see if it scales nicely:
./magic.py 1291 693
Outputs:
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
So we see that this approach also does work well. The only problem I have with it is that you have to set that magic_height
parameter or equivalent.
Fixed DPI + set_size_inches
This approach gave a slightly wrong pixel size, and it makes it is hard to scale everything seamlessly.
set_size_inches.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
0,
60.,
'Hello',
# Keep font size fixed independently of DPI.
# https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
'set_size_inches.png',
format='png',
)
Run:
./set_size_inches.py 431 231
Outputs:
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
So the height is slightly off, and the image:
The pixel sizes are also correct if I make it 3 times larger:
./set_size_inches.py 1291 693
Outputs:
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
We understand from this however that for this approach to scale nicely, you need to make every DPI-dependant setting proportional to the size in inches.
In the previous example, we only made the «Hello» text proportional, and it did retain its height between 60 and 80 as we’d expect. But everything for which we didn’t do that, looks tiny, including:
- line width of axes
- tick labels
- point markers
SVG
I could not find how to set it for SVG images, my approaches only worked for PNG, e.g.:
get_size_svg.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size_svg.svg',
format='svg',
dpi=height/fig.get_size_inches()[1]
)
Run:
./get_size_svg.py 431
And the generated output contains:
<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"
And identify says:
get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000
And if I open it in Chromium 86 the browser debug tools mouse image hover confirm that height as 460.79.
But of course, since SVG is a vector format, everything should in theory scale, so you can just convert to any fixed sized format without loss of resolution, e.g.:
inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png
gives the exact height:
I use Inkscape instead of ImageMagick’s convert
here because you need to mess with -density
as well to get sharp SVG resizes with ImageMagick:
- https://superuser.com/questions/598849/imagemagick-convert-how-to-produce-sharp-resized-png-files-from-svg-files/1602059#1602059
- How to convert a SVG to a PNG with ImageMagick?
And setting <img height=""
on the HTML should also just work for the browser.
It was tested on matplotlib 3.2.2.
In this article, we will see how to change the size of the Figures In Matplotlib in Python.
How to use it for plotting?
The main purpose of Matplotlib is to create a figure representing data. The use of visualizing data is to tell stories by curating data into a form easier to understand, highlighting the trends and outliers. We can populate the figure with all different types of data, including axes, a graph plot, a geometric shape, etc. “When” we plot graphs we may want to set the size of a figure to a certain size. You may want to make the figure wider in size, taller in height, etc.
Increase or decrease the plot size in Matplotlib
This can be achieved by an attribute of Matplotlib known as figsize. The figsize attribute allows us to specify the width and height of a figure in-unit inches.
Syntax of matplotlib.pyplot
Syntax:
import matplotlib.pyplot as plt
figure_name = plt.figure(figsize=(width, height))
The figsize attribute is a parameter of the function figure(). It is an optional attribute, by default the figure has the dimensions as (6.4, 4.8). This is a standard plot where the attribute is not mentioned in the function.
Normally each unit inch is of 80 x 80 pixels. The number of pixels per unit inch can be changed by the parameter dpi, which can also be specified in the same function.
Approach:
- We create a variable plt_1, and set it equal to, plt.figure(figsize=(6,3)).
- This creates a figure object, which has a width of 6 inches and 3 inches in height.
- The values of the figsize attribute are a tuple of 2 values.
Example 1: Set the figure size Argument
Python3
import
matplotlib.pyplot as plt
plt_1
=
plt.figure(figsize
=
(
6
,
3
))
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
This works if you’re using a python IDE other than Jupiter notebooks. If you are using Jupiter notebooks, then you would not use, plt.show(). Instead, you would specify in the Code right after importing matplotlib, %matplotlib inline.
Example 2: Change Figure Size in Matplotlib
To see the dynamic nature of figure sizing in Matplotlib, now we have to create a figure with the dimensions inverted. The height will now be double the size of the width.
Python3
import
matplotlib.pyplot as plt
plt_1
=
plt.figure(figsize
=
(
3
,
6
))
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
Example 3: Set the Height and Width of a Figure in Matplotlib
In this example, we will see that instead of simply using figsize we can also set the height and width of the plot using set_figheight() and set_figwidth() functions.
Python3
import
matplotlib.pyplot as plt
fig
=
plt.figure()
fig.set_figheight(
5
)
fig.set_figwidth(
10
)
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
Example 4: Set the Height and Width of a Figure in Inches.
Here, we will see another example of setting figure size in inches using set_size_inches(5, 5).
Python3
import
matplotlib.pyplot as plt
fig
=
plt.figure()
fig.set_size_inches(
5
,
5
)
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
In this article, we will see how to change the size of the Figures In Matplotlib in Python.
How to use it for plotting?
The main purpose of Matplotlib is to create a figure representing data. The use of visualizing data is to tell stories by curating data into a form easier to understand, highlighting the trends and outliers. We can populate the figure with all different types of data, including axes, a graph plot, a geometric shape, etc. “When” we plot graphs we may want to set the size of a figure to a certain size. You may want to make the figure wider in size, taller in height, etc.
Increase or decrease the plot size in Matplotlib
This can be achieved by an attribute of Matplotlib known as figsize. The figsize attribute allows us to specify the width and height of a figure in-unit inches.
Syntax of matplotlib.pyplot
Syntax:
import matplotlib.pyplot as plt
figure_name = plt.figure(figsize=(width, height))
The figsize attribute is a parameter of the function figure(). It is an optional attribute, by default the figure has the dimensions as (6.4, 4.8). This is a standard plot where the attribute is not mentioned in the function.
Normally each unit inch is of 80 x 80 pixels. The number of pixels per unit inch can be changed by the parameter dpi, which can also be specified in the same function.
Approach:
- We create a variable plt_1, and set it equal to, plt.figure(figsize=(6,3)).
- This creates a figure object, which has a width of 6 inches and 3 inches in height.
- The values of the figsize attribute are a tuple of 2 values.
Example 1: Set the figure size Argument
Python3
import
matplotlib.pyplot as plt
plt_1
=
plt.figure(figsize
=
(
6
,
3
))
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
This works if you’re using a python IDE other than Jupiter notebooks. If you are using Jupiter notebooks, then you would not use, plt.show(). Instead, you would specify in the Code right after importing matplotlib, %matplotlib inline.
Example 2: Change Figure Size in Matplotlib
To see the dynamic nature of figure sizing in Matplotlib, now we have to create a figure with the dimensions inverted. The height will now be double the size of the width.
Python3
import
matplotlib.pyplot as plt
plt_1
=
plt.figure(figsize
=
(
3
,
6
))
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
Example 3: Set the Height and Width of a Figure in Matplotlib
In this example, we will see that instead of simply using figsize we can also set the height and width of the plot using set_figheight() and set_figwidth() functions.
Python3
import
matplotlib.pyplot as plt
fig
=
plt.figure()
fig.set_figheight(
5
)
fig.set_figwidth(
10
)
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
Example 4: Set the Height and Width of a Figure in Inches.
Here, we will see another example of setting figure size in inches using set_size_inches(5, 5).
Python3
import
matplotlib.pyplot as plt
fig
=
plt.figure()
fig.set_size_inches(
5
,
5
)
x
=
[
1
,
2
,
3
,
4
,
5
]
y
=
[x
*
2
for
x
in
x]
plt.plot(x, y)
plt.show()
Output:
In this tutorial, you’ll learn how to change the plot and figure sizes in Matplotlib. Data visualization is a valuable tool to help you communicate your data. Being able to customize exactly how your plots are sized gives you the flexibility to produce your desired results. This allows you to produce print-ready visualizations.
By the end of this tutorial, you’ll have learned:
- How to change the plot and figure size using measurements in inches
- How to set the DPI of a plot and figure
- How to change the size of a plot by a factor of its size
Loading a Sample Plot
To follow along with this tutorial line by line, copy and paste the code below into your favourite code editor. We’ll be using a simple plot for this tutorial, in order to really focus on how to change the figure size of your plot in Matplotlib.
# Loading a Sample Plot
import matplotlib.pyplot as plt
x = range(1, 11)
y = [i**2 for i in x]
plt.plot(x, y)
plt.show()
This returns the following image:
Let’s break down what we did here:
- We loaded the
pyplot
module asplt
- We defined
x
values as the values from 1 through 10 - We then used a Python list comprehension to define the
y
values as the square of eachx
value - We then passed these variables into the
plt.plot()
function - Finally, we used the
.show()
method to display the visualization
Changing Plot Size in Matplotlib Using figsize
One of the simplest and most expressive ways of changing the plot size in Matplotlib is to use the figsize=
argument. As the name of the argument indicates, this is applied to a Matplotlib figure. Because of this, we first need to instantiate a figure in which to host our plot.
Let’s take a look at how we can do this:
# Changing the figure size using figsize=
import matplotlib.pyplot as plt
x = range(1, 11)
y = [i**2 for i in x]
plt.figure(figsize=(5, 5))
plt.plot(x, y)
plt.show()
This returns the following image:
In the code above, we accessed the Figure
that was created by default. In the code above, we assigned the figsize=
parameter in order to specify the size of the figure we want to use. We passed in a tuple containing the width and the length in inches.
If you’re more accustomed to working with centimeters, you first need to convert the measurement to centimeters. This can be done by multiplying a value in inches by 2.54 to calculate it in centimeters.
Setting the DPI of a Matplotlib Figure
Matplotlib allows you to prepare print-friendly reports. In order to finely tune your printable reports, you can also control the DPI of the charts your produce. By default, Matplotlib uses a DPI of 100 pixels per inch. In order to mofidy this, you can use the dpi=
parameter on the figure object.
Let’s change our DPI to 200 pixels per inch:
# Changing the DPI of a Matplotlib Chart
import matplotlib.pyplot as plt
x = range(1, 11)
y = [i**2 for i in x]
plt.figure(figsize=(5, 5), dpi=200)
plt.plot(x, y)
plt.show()
This returns the following image:
In the next section, you’ll learn how to use Matplotlib to set width and height individually.
Changing Plot Size in Matplotlib Using set_figheight and set_figwidth
Matplotlib also provides ways to more explicitly define the height and width individually, using the set_fightheight()
and set_figwidth()
functions. While the previous section showed you how to change the size in one argument, these functions give you the control to modify these parameters individually.
Let’s see how we can use these functions to modify the size of our plot in Matplotlib:
# Using Figure Functions to Change Matplotlib Chart Size
import matplotlib.pyplot as plt
x = range(1, 11)
y = [i**2 for i in x]
# Create a figure
fig = plt.figure()
# Set the width and height
fig.set_figwidth(4)
fig.set_figheight(6)
# Create an axes
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.show()
This returns the following image:
Let’s break down what we did here:
- We declared a figure object
- We then used the
set_figwidth()
andset_figheight()
functions to control the figure size - We then declared a subplot axes and added our plot
In the next section, you’ll learn how to use the rcParams
in Matplotlib to change plot sizes.
Changing Plot Size in Matplotlib Using rcParams
We can change the figure size in Matplotlib globally using the rcParams
available. This allows you to produce multiple visualizations and only modify the size a single time. This can be very valuable when you want to generate multiple plots and need them all to be the same size.
Let’s see how we can use rcParams to control the figure size in Matplotlib:
# Using rcParams to Change Figure Size in Matplotlib
import matplotlib.pyplot as plt
x = range(1, 11)
y = [i**2 for i in x]
plt.rcParams['figure.figsize'] = (8, 4)
plt.plot(x, y)
plt.show()
This returns the following image:
In the code above, we accessed the rcParams dictionary key for figure.figsize in order to pass in a tuple that contained the width and height of the figure.
Conclusion
In this tutorial, you learned how to change the figure size of a Matplotlib plot. You learned how to change the size of a plot using the figsize=
parameter. Then, you learned how to use the figure object functions, set_figheight()
and set_figwidth()
functions to change the size of a Matplotlib plot. Finally, you learned how to use rcParams to change the size of a Matplotlib chart. You also learned how to control the DPI of a Matplotlib visualization.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Plotting in Python with Matplotlib
- Matplotlib Scatter Charts – Learn all you need to know
- Matplotlib Bar Charts – Learn all you need to know
- Matplotlib Line Charts – Learn all you need to know
In this Python Matplotlib tutorial, we’ll discuss the Matplotlib increase plot size in python. Here we will cover different examples related to the increase of the plot size using matplotlib. Moreover, we’ll also cover the following topics:
- Matplotlib increase plot size
- Matplotlib increase plot size jupyter
- Matplotlib increase plot size subplots
- Matplotlib pyplot set_size_inches
- Pandas matplotlib increase plot size
- Matplotlib change figure size and dpi
- Matplotlib plot change point size
- Matplotlib set plot size in pixels
- Matplotlib change default plot size
- Matplotlib change bar plot size
- Matplotlib change scatter plot size
- Matplotlib set plot window size
- Matplotlib change figure size fig ax
- Matplotlib set plot size in centimeter
Plots are a great method to graphically depict data and summarise it in a visually attractive way. However, if not plotted properly, it appears to be complex.
In matplotlib, we have several libraries for the representation of data. While creating plots in matplotlib, it is important for us to correct their size, so that we properly visualize all the features of the plot.
Also, check: Matplotlib plot a line
Matplotlib increase plot size jupyter
In this section, we’ll learn to increase the size of the plot using matplotlib in a jupyter notebook.
The syntax is given below:
matplotlib.pyplot.rcParams["figure.figsize"]
The above syntax is used to increase the width and height of the plot in inches. By default, the width is 6.4 and the height is 4.8.
Let’s see examples:
Example #1
Here we’ll see an example to increase the size of the plot in the jupyter notebook.
# Import Library
import matplotlib.pyplot as plt
# Increase size of plot in jupyter
plt.rcParams["figure.figsize"] = (8,5.5)
# Define Data
x = [2, 4, 6, 8]
y = [5, 10, 15, 20]
# Plot
plt.plot(x, y, '-.')
# Display
plt.show()
- Firstly, import the matplotlib.pyplot library
- Next, to increase the size of the plot in the jupyter notebook use plt.rcParams[“figure.figsize”] method and set width and height of the plot.
- Then, define the data coordinates used for plotting.
- To plot a graph, use the plot() function and also set the style of the line to dot-dash.
- To display the plot, on the user’s screen use the show() function.
Example #2
The source code below elaborates the process of increasing size in a jupyter notebook using matplotlib.
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Increase size of plot in jupyter
plt.rcParams["figure.figsize"] = (10,6)
# Define Data
x = np.linspace(0, 10, 1000)
y = np.sin(x)
# Plot
plt.plot(x, y)
# Display
plt.show()
Here we define data coordinates by using linspace() function and sin() function of numpy module.
Read: What is matplotlib inline
Matplotlib increase plot size subplots
Here we’ll learn to increase the plot size of subplots using matplotlib. There are two ways to increase the size of subplots.
- Set one size for all subplots
- Set individual sizes for subplots
Set one size for all subplots
Here we’ll see examples where we set one size for all the subplots.
The following is the syntax:
fig, ax = plt.subplots(nrows , ncols , figsize=(width,height))
Example #1
Here is the example where we increase the same size for all the subplots.
# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np
# Set one size for all subplot
fig, ax = plt.subplots(2, 2, figsize=(10,8))
# Preparing the data to subplots
x = np.linspace(0,10,100)
y1 = x ** 2
y2 = x ** 4
y3 = x ** 6
y4 = x ** 8
# Plot
ax[0, 0].plot(x, y1, color='r')
ax[0, 1].plot(x, y2, color='k', linestyle=':')
ax[1, 0].plot(x, y3, color='y', linestyle='-.')
ax[1, 1].plot(x, y4, color='c',linestyle='--')
# Display
plt.show()
- Import necessary libraries, such as matplotlib.pyplot, and numpy.
- Then create subplots with 2 rows and 2 columns, using the subplots() function.
- To set one size for all subplots, use the figsize() function with width and height parameters.
- Define data coordinates used for plotting.
- To plot the subplots, use the plot() function with axes.
- To set different linestyles of the plotted lines, use linestyle parameter.
- To visualize the subplots, use the show() function.
Example #2
Let’s see one more example to set the same size for all the subplots to understand the concept more clearly.
# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np
# Change the figure size
plt.figure(figsize=[15,14])
# Preparing the data to subplots
x = np.linspace(0, 10, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
# Plot the subplots
# Plot 1
plt.subplot(2, 2, 1)
plt.plot(x, y1, color='g')
# Plot 2
plt.subplot(2, 2, 2)
plt.plot(x, y2, color='k')
# Display
plt.show()
- To define data coordinates, we use linspace(), sin() and cos() functions of numpy.
- Here we increase the size of all subplots, using the figure() method and we pass the figsize() as a parameter and set the width and height of the subplots.
Set individual sizes for subplots
Here we’ll see different examples where we set individual sizes for subplots using matplotlib.
The following is the syntax:
fig, ax = plt.subplots(nrows, ncols, gridspec_kw=
{'width_ratios': [3, 1],
'height_ratios’: [3, 3]})
Example:
The source code below elaborates the process of increasing the size of the individual subplots.
# Import Library
import matplotlib.pyplot as plt
# Define subplots
fig, ax = plt.subplots(1, 2,
gridspec_kw={'width_ratios': [8,15]})
# Define data
x = [1, 2, 3, 4, 5]
y1 = [7, 13, 24, 26, 32]
y2 = [2, 4, 6, 8, 10]
# Create subplots
ax[0].plot(x, y1, color='red', linestyle=':')
ax[1].plot(x, y2, color='blue', linestyle='--')
# Adjust padding
plt.tight_layout()
# Display
plt.show()
- Import matplotlib.pyplot library.
- Then create subplots with 1 row and 2 columns, using the subplots() function.
- To set the individual sizes for subplots, use gridspec_kw() method. The gridpec_kw is a dictionary with keywords that can be used to change the size of each grid.
- Next, define data coordinates to plot data.
- To plot a line chart, use plot() function.
- To auto adjust padding, use tight_layout() function.
- To visualize the subplots, use show() function.
Example #2
The process of increasing the size of specific subplots is explained in the source code below.
# Import Library
import matplotlib.pyplot as plt
# Define subplots
fig, ax = plt.subplots(1, 2, gridspec_kw={'width_ratios':
[10,4]})
# Define data
x = np.arange(0, 30, 0.2)
y1 = np.cos(x)
y2 = np.sin(x)
# Create subplots
ax[0].plot(x, y1, color='red', linestyle=':')
ax[1].plot(x, y2, color='blue', linestyle='--')
# Adjust padding
plt.tight_layout()
# Display
plt.show()
To plot a data, we define data coordinates, by using arange(), cos() and sin() functions of numpy.
Read: Matplotlib plot bar chart
Matplotlib pyplot set_size_inches
In matplotlib, to set the figure size in inches, use the set_size_inches() method of the figure module.
The following is the syntax:
matplotlib.figure.Figure.set_size_inches(w, h)
Here w represents the width and h represents the height.
Let’s see different examples:
Example #1
Here is an example to increase the plot size by using the set_size_inches method.
# Import Libraries
import matplotlib.pyplot as plt
# Create figure
fig = plt.figure()
# Figure size
fig.set_size_inches(6.5, 6)
# Define Data Coordinates
x = [10, 20, 30, 40, 50]
y = [25, 25, 25, 25, 25]
# Plot
plt.plot(x, y, '--')
plt.plot(y, x)
# Display
plt.show()
- Import matplotlib.pyplot library.
- Next, create a new figure by using the figure() function.
- To set the figure size in inches, use the set_size_inches() function and pass the width and the height as a parameter, and set their value to 6.5 and 6 respectively.
- Then, define the x and y data coordinates used for plotting.
- To plot the line chart, use the plot() function.
Example #2
Here we create a line chart using x and y coordinates (define by arange and sin function). We set the width of the plot to 12 and the height to 10 inches by using the set_size_inches function.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Create figure
fig = plt.figure()
# Figure size
fig.set_size_inches(12,10)
# Define Data Coordinates
x = np.arange(0,4*np.pi,0.1)
y = np.sin(4*x)
# Plot
plt.plot(x, y, '--')
# Display
plt.show()
Here we define x and y data coordinates by using arange(), pi, and sin() function of numpy.
Read: Matplotlib subplots_adjust
Pandas matplotlib increase plot size
In Pandas, the figsize parameter of the plot() method of the matplotlib module can be used to change the size of a plot bypassing required dimensions as a tuple. It is used to calculate the size of a figure object.
The following is the syntax:
figsize=(width, height)
Width and height must be in inches.
Let’s see different examples:
Example #1
In this example, we’ll create a pie chart using pandas dataframe and increase the size of the plot.
# Import Library
import pandas as pd
# Creat pandas dataframe
df = pd.DataFrame({'Owner': [50, 15, 8, 20, 12]},
index=['Dog', 'Cat', 'Rabbit',
'Parrot','Fish'])
# Plot
df.plot.pie(y='Owner', figsize=(8,8))
# Display
plt.show()
- Import the pandas module.
- After this, create a pandas dataframe with an index.
- To plot a pie chart, use df.plot.pie() function.
- To increase the size of the plot, pass the figsize() parameter along with dimensions.
Example #2
We’ll make a line chart with a pandas dataframe and increase the plot size in this example.
# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Data
data = {'Year': [2021, 2020, 2019, 2018, 2017, 2016, 2015,
2014],
'Birth_Rate': [17.377, 22.807, 26.170, 18.020, 34.532,
18.636, 37.718, 19.252]
}
# Create DataFrame
df = pd.DataFrame(data,columns=['Year','Birth_Rate'])
# Line Plot
df.plot(x ='Year', y='Birth_Rate', kind = 'line',
figsize=(8,6))
# Display
plt.show()
- Create a dataframe in pandas using the DataFrame() method.
- Next, plot the DataFrame using df.plot() function.
- Here we set the kind parameter to the line in order to plot the line chart.
- To increase the size of the plot, pass the figsize() parameter along with dimensions.
Read: Matplotlib set y axis range
Matplotlib change figure size and dpi
Here we’ll learn to change the figure size and the resolution of the figure using matplotlib module.
The following is the syntax:
matplotlib.pyplot.figure(figsize=(w,h), dpi)
Let’s see examples related to this:
Example #1
In this example, we plot a line chart and change its size and resolution.
# Import Libraries
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
# Set fig size and dpi
figure(figsize=(8,6), dpi=250)
# Define Data
x = range(0,12)
# Plot
plt.plot(x)
# Display
plt.show()
- First use matplotlib.pyplot.figure to create a new figure or activate one that already exists.
- The method takes a figsize argument, which is used to specify the figure’s width and height (in inches).
- Then, enter a dpi value that corresponds to the figure’s resolution in dots-per-inch.
Example #2
Here we’ll see one more example related to the change in size and resolution of the figure to understand the concept more clearly.
# Import Libraries
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import numpy as np
# Set fig size and dpi
figure(figsize=(6,4), dpi=150)
# Define Data
x = np.random.randint(450,size=(80))
# Plot
plt.plot(x)
# Display
plt.show()
- To define data coordinates, here we use random.randint() method of numpy.
- Here we set the width, height, and dpi of the figure to 6, 4, and 150 respectively.
Read: Matplotlib update plot in loop
Matplotlib plot change point size
Here we’ll learn how to change marker size in matplotlib with different examples.
The following is the syntax:
matplotlib.pyplot.scatter(x , y , s)
Here x and y specify the data coordinates and s specify the size of the marker.
Example #1
Here we’ll see an example where we set a single size for all the points.
# Import Library
import matplotlib.pyplot as plt
# Define Data
A = [6, 7, 2, 5, 4, 8]
B = [12, 14, 17, 20, 22, 27]
# Scatter Plot and set size
plt.scatter(A, B, s=80)
# Display
plt.show()
- Import matplotlib.pyplot library.
- Next, define A and B data coordinates.
- To plot a scatter graph, use the scatter() function.
- To set the same size to all points, use s as an argument and set the size.
- To visualize the pot, use the show() function.
Example #2
Here we’ll see an example where we set different sizes for each point
# Import Library
import matplotlib.pyplot as plt
# Define Data
x = [6, 7, 2, 5, 4, 8]
y = [12, 14, 17, 20, 22, 27]
# Define Size
sizes = [20, 55, 85, 150, 250, 9]
# Scatter Plot and set size
plt.scatter(x, y, s=sizes)
# Display
plt.show()
- Import matplotlib.pyplot library.
- Next, define data coordinates.
- Then, define different sizes for each point.
- To plot a scatter graph, use the scatter() function and set the size pass s parameter.
- To display the plot, use the show() function.
Example #3
Here we’ll see an example where we define the point size for each point in the plot.
# Import Library
import matplotlib.pyplot as plt
# Define Data
x = [2, 4, 6, 8, 10, 12, 14, 16]
y = [4, 8, 12, 16, 20, 24, 28, 32]
# Define Size
sizes = [3**n for n in range(len(x))]
# Scatter Plot and set size
plt.scatter(x, y, s=sizes, color='red')
# Display
plt.show()
- Import matplotlib.pyplot library for data visualization.
- Define data coordinates.
- Create a function to define the point sizes to use for each point in the plot.
- To plot a scatter graph, use the scatter() function.
Read: Matplotlib Pie Chart Tutorial
Matplotlib set plot size in pixels
Here we’ll see examples where we convert inches to pixels and plot the graph using matplotlib module.
Example #1
In the below example we’ll change the plot size by using the pixel conversion method.
# Import Libraries
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import numpy as np
px = 1/plt.rcParams["figure.dpi"]
# Set fig size in Pixel
figure(figsize=(600 * px , 450 * px))
# Define Data
x = np.random.randint(800,size=(120))
# Plot
plt.plot(x)
# Display
plt.show()
- Import necessary libraries such as matplotlib.pyplot, figure, and numpy.
- Then use, default pixels values, rcParams[‘figure.dpi’] to set values to px.
- Now, set figsize in pixels.
- Then, define the data coordinates for plotting.
- To plot the line chart, use the plot() function.
- To display the plot, use the show() function.
Example #2
Here we change the plot size in pixels by using the dpi argument.
# Import Libraries
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
# Set fig size and dpi
figure(dpi=100)
# Define Data Coordinates
water_quantity = [17, 27, 14, 22, 16, 6]
# Add labels
water_uses = ['Shower', 'Toilet', 'Leaks', 'Clothes Wsher',
'Faucet', 'Other']
# Colors
colors =['salmon','palegreen','skyblue','plum','pink','silver']
# Plot
plt.pie(water_quantity, colors=colors)
# Add legend
plt.legend(labels=water_uses, fontsize=18, loc='upper center',
bbox_to_anchor=(0.5, -0.04), ncol=2)
# Display
plt.show()
- Here we use, the dpi parameter to set the plot in pixels with the figure() function.
- Next, we define data coordinates, labels, and colors for pie chart creation,
- To plot a pie chart, we use the pie() function.
- To add a legend to a plot, we use the legend() function.
Read: Matplotlib scatter plot color
Matplotlib change default plot size
In Matplotlib, the dictionary object rcParams contains the properties. The figure size could be used as the key figure’s value in figsize in rcParams, which represents the size of a figure.
To change the size by default, we use plt.rcParams. It is acceptable when we placed it before or after plt.plot. Any figure made using the same scripts will be assigned the same figure size.
Let’s see examples:
Example #1
Here we’ll set the default, size of the figure to 7 by 7.
# Import Library
import matplotlib.pyplot as plt
# Default plot size
plt.rcParams["figure.figsize"] = (7,7)
# Plot
plt.plot([[5, 6], [9, 10], [1, 2], [1, 2]])
# Show
plt.show()
- Import matplotlib.pyplot library.
- To set default plot size, use plt.rcParams[“figure.figsize”].
- To plot a chart, use the plot() function.
Read: Matplotlib Plot NumPy Array
Matplotlib change bar plot size
Here we’ll learn the different ways to change the size of the bar plot using the matplotlib module with the help of examples.
Example #1
Here we’ll use the figsize() method to change the bar plot size.
# Import Library
import matplotlib.pyplot as plt
# Change size
plt.figure(figsize=(9,7))
# Define Data
pets = ['Rabbit', 'Dog', 'Cat', 'Goldfish', 'Parrot']
no_of_people = [4, 8, 11, 6, 5]
# Plot bar chart
plt.bar(pets, no_of_people)
# Display
plt.show()
- Import matplotlib.pyplot library.
- To change the figure size, use figsize argument and set the width and the height of the plot.
- Next, we define the data coordinates.
- To plot a bar chart, use the bar() function.
- To display the chart, use the show() function.
Example #2
In this example, we’ll change the size of the bar chart by using rcParams.
# Import Library
import matplotlib.pyplot as plt
# Change size
plt.rcParams['figure.figsize']=(8,6.5)
# Define Data
school_suppiles = ['Pencil', 'Scale', 'Pen', 'Sharpner',
'Eraser']
no_of_suppiles = [8, 3, 2, 5, 4]
# Plot bar chart
plt.bar(school_suppiles, no_of_suppiles)
# Display
plt.show()
Here we use the default method, to change the size of bar plots i.e. by using plt.rcParams[‘figure.figsize’].
Read: Matplotlib set_xticklabels
Matplotlib change scatter plot size
Here we’ll learn the different ways to change the size of the scatter plot using the matplotlib module with the help of examples.
Example #1
Here we’ll learn to change the size of scatter plot by using figsize.
# Import Library
import matplotlib.pyplot as plt
# Set size
plt.figure(figsize=(8,5))
# Define Dataset
x1 = [45, 58, 29, 83, 95, 20,
98, 27]
y1 = [31, 75, 8, 29, 79, 55,
43, 72]
x2 = [23, 41, 25, 64, 3, 15,
39, 66]
y2 = [26, 34, 38,
20, 56, 2, 47, 15]
# Plot Scatter Graph
plt.scatter(x1, y1, c ="cyan",
marker ="s",
edgecolor ="black",
s = 50)
plt.scatter(x2, y2, c ="yellow",
linewidths = 2,
marker ="^",
edgecolor ="red",
s = 200)
# Display
plt.show()
- Import matplotlib.pyplot library.
- To set figure size, use the figsize parameter and set the width and height of the figure.
- Define datasets to plot to scatter graph.
- To plot a scatter plot, use the scatter method.
- To add extra features to the plot, pass color, size, marker, edgecolor, marker as a parameter.
Example #2
In this example, we use the set_size_inches method change the size of the scatter plot.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Create figure
fig = plt.figure()
# Figure size
fig.set_size_inches(6,8)
# Define Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Plot
plt.scatter(x, y)
# Display
plt.show()
- Import necessary libraries such as matplotlib.pyplot and numpy.
- Then create a new figure by using the figure() method.
- To set the size of the scatter plot, use the set_size_inches() method and pass width and height.
- To define data coordinates, use linspace() and sin() methods.
- To plot a scatter graph, use the scatter() function.
Read: Matplotlib tight_layout – Helpful tutorial
Matplotlib change figure size fig ax
We can easily change the height and the width of the plot by using the set_figheight and the set_figwidth method of the matplotlib module.
Let’s see examples related to this concept:
Example #1
Here we set the width of the plot, by using the set_figwidth method.
# Import Library
import numpy as np
import matplotlib.pyplot as plt
# Set width
fig = plt.figure()
fig.set_figwidth(8)
# Data Coordinates
x = np.arange(2, 8)
y = np.array([5, 8, 6, 20, 18, 30])
# Plot
plt.plot(x, y, linestyle='--')
# Display
plt.show()
- First import necessary libraries, such as numpy and matplotlib.pyplot.
- Next, use the set_figwidth() method to change the width of the plot.
- To define data coordinates, use arange() and array() methods of numpy.
- To plot a line graph with a dashed line style, use the plot() function with linestyle parameter.
Example #2
Here we set the height of the plot, by using the set_figheight method.
# Import Library
import numpy as np
import matplotlib.pyplot as plt
# Set height
fig = plt.figure()
fig.set_figheight(8)
# Data Coordinates
x = np.arange(2, 8)
y = np.array([5, 8, 6, 20, 18, 30])
# Plot
plt.plot(x, y, linestyle='--')
# Display
plt.show()
- First import necessary libraries, such as numpy and matplotlib.pyplot.
- Next, use the set_figheight() method to change the height of the plot.
- To define data coordinates, use arange() and array() methods of numpy.
Read: Matplotlib x-axis label
Matplotlib set plot size in centimeter
In matplotlib by default, the figure size is in inches. Here we’ll learn to set plot size in centimeter with the help of an example.
Example:
# Import Library
import numpy as np
import matplotlib.pyplot as plt
# Set Size
cm = 1/2.54
plt.figure(figsize=(15*cm, 11*cm))
# Data Coordinates
x = np.arange(2, 8)
y = x * 2 + 6
# Plot
plt.plot(x, y)
# Display
plt.show()
- Import numpy library.
- Next, import the matplotlib library.
- Set figure size by conversion inches to centimeters.
- Define data coordinates x and y.
- To plot a line chart, we use the plot() function.
You may also like to read the following Matplotlib tutorials.
- Matplotlib scatter plot legend
- Matplotlib multiple bar chart
- Stacked Bar Chart Matplotlib
- Matplotlib multiple plots
- Draw vertical line matplotlib
In this Python tutorial, we have discussed the “Matplotlib increase plot size” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.
- Matplotlib increase plot size
- Matplotlib increase plot size jupyter
- Matplotlib increase plot size subplots
- Matplotlib pyplot set_size_inches
- Pandas matplotlib increase plot size
- Matplotlib change figure size and dpi
- Matplotlib plot change point size
- Matplotlib set plot size in pixels
- Matplotlib change default plot size
- Matplotlib change bar plot size
- Matplotlib change scatter plot size
- Matplotlib set plot window size
- Matplotlib change figure size fig ax
- Matplotlib set plot size in centimeter
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Have you recently started working on graphs and plots using the matplotlib library and don’t know how to change the size of the figures according to your will? Don’t worry. In this article, we will help you manage the size of the plots as you like. If you have not explored the world of matplotlib until now, you can start from here. So, let us learn how to use the matplotlib figsize attribute to adjust the size of the graph.
Matplotlib Figsize is a method used to change the dimension of your matplotlib window. Currently, the window is generated of 6.4×4.8 inches by default. Using this module, you can change it at any size.
What is Figsize in Python?
Matplotlib Figsize is a method from the pyplot class which allows you to change the dimensions of the graph. As every dimension in generated graphs is adjusted by the library, it can be quite difficult to visualize data in a proper format. As a result, the figsize method is very useful to customize the dimensions as well as layouts of the graphs.
We can make the figure taller in size, broader by changing the size in inches.
To make a plot or a graph using matplotlib, we first have to install it in our system using pip install matplotlib.
Also, figsize is an attribute of figure() class of pyplot submodule of matplotlib library. So, the syntax is something like this-
matplotlib.pyplot.figure(figsize=(float,float))
Parameters-
- Width – Here, we have to input the width in inches. The default width is 6. To broaden the plot, set the width greater than 1. And to make the graph less broad, set the width less than 6.
- Height – Here, we have to input the height of the graph. The default value is 4. To increase the length, set the height greater than 4, and to decrease the height set the height less than 4.
What is default Figsize Matplotlib?
In Matplotlib all the diagrams are created at a default size of 6.4 x 4.8 inches. This size can be changed by using the Figsize method of the respective figure. This parameter is governed under the rcParams attribute of the figure. By using Figsize, you can change both of these values.
The default figure size values are stored as a list of two float objects. For example, rcParams[“figure. figsize”] will be equal to [6.4, 4.8] in a programmatic way.
What is rcParams figure Figsize?
rcParams is a dictionary attribute in Matplotlib figure class that allows you to customize the look of your graph. This attribute is responsible for carrying data of figure size, figure DPI, figure facecolor, and figure edgecolor. All of these are initialized to default values of [6.4, 4.8], 100, ‘w’, and ‘w’ respectively.
Figsize is a key in rcParams which changes the figure size of your data visualization. As of now, you cannot change the rcParams directly, but you can use different methods like figsize to do it.
What are Matplotlib Figsize Units?
Matplotlib have general way of keeping all the distances in inches. For figsize too, the units are measured in inches by default. if you want a to use a different unit for the figsize, you can achieve it by creating a converting function. Following example explains a way to initialize the Figsize in centimeters (cm) –
Code –
import matplotlib.pyplot as plt import numpy as np def cm_to_inch(value): return value/2.54 x = np.arange(0, 10, 0.1) y = np.sin(x) plt.figure(figsize=(cm_to_inch(25), cm_to_inch(15))) plt.plot(x, y) plt.show()
Output –
Explanation –
We first start by importing the matplotlib library. Then we create an array of x-axis whose value ranges from 0 to 10 at 0.1 intervals. np.sin() function generates a sine wave function values. The function cm_to_inch() converts all the values of centimeters to inches and initializes the dimensions of the figure.
Changing the Height and Width of the Graph
Both height and width can be changed by the figure.figsize() method. Following example demonstrates the figures with default size and after them are the customized figures of different dimensions.
Graph with Default Size
Let us first know how to make a graph without setting any specific size and see if it is our desirable size or not.
We will create a simple plot by creating our own data.
import matplotlib.pyplot as plt x=[1,2,3,4,5,6,7,8,9] y=[i**2 for i in x] plt.plot(x,y) plt.title("Plot of Default Size")
Changing the Height using Matplotlib Figsize
Suppose we have a pandas data frame that contains information about some sports and how many people play those sports. Something like this-
We want to make a bar chart from it, let us first make a graph with the default size. I have made that data frame in the form of an array to make the task easy.
# import the pyplot submodule of matplotlib library # and rename it as plt import matplotlib.pyplot as plt # name of the sports sports_name=['Aquatics', 'Athletics', 'Rowing', 'Gymnastics', 'Fencing', 'Football','Hockey', 'Wrestling', 'Shooting', 'Sailing', 'Cycling','Canoe / Kayak', 'Basketball', 'Volleyball', 'Equestrian', 'Handball','Boxing', 'Weightlifting', 'Judo', 'Baseball', 'Archery', 'Tennis','Rugby', 'Softball', 'Modern Pentathlon', 'Table Tennis', 'Badminton','Tug of War', 'Taekwondo', 'Polo', 'Lacrosse', 'Golf', 'Ice Hockey','Skating', 'Cricket', 'Triathlon', 'Rackets', 'Croquet','Water Motorsports', 'Basque Pelota', 'Jeu de paume', 'Roque'] # These are people which play the respective sport people_playing_the_sports=[3828, 3448, 2523, 2214, 1547, 1387, 1325,140,105,1061,1025,1002,940,910,894,886,842,548,435,335,305,272,192,180,174,120,120,94,80,66,59,30,27,27,24,18,10,8,5,4,3,3] # To create a bar graph use bar function of pyplot plt.bar(sports_name,people_playing_the_sports) # Rotate the name of sports by 90 degree in x-axis plt.xticks(rotation=90) # show the graph plt.show()
We can see that due to a lack of space, the graph is too untidy. For a better-looking graph, we need to change the width of the graph. Let us see how we will do that.
import matplotlib.pyplot as plt people_playing_the_sports=[3828, 3448, 2523, 2214, 1547, 1387, 1325,1140,105,1061,1025,1002,940,910,894,886,842,548,435,335,305,272,192,180,174,120,120,94,80,66,59,30,27,27,24,18,10,8,5,4,3,3] sports_name=['Aquatics', 'Athletics', 'Rowing', 'Gymnastics', 'Fencing', 'Football','Hockey', 'Wrestling', 'Shooting', 'Sailing', 'Cycling','Canoe / Kayak', 'Basketball', 'Volleyball', 'Equestrian', 'Handball','Boxing', 'Weightlifting', 'Judo', 'Baseball', 'Archery', 'Tennis','Rugby', 'Softball', 'Modern Pentathlon', 'Table Tennis', 'Badminton','Tug of War', 'Taekwondo', 'Polo', 'Lacrosse', 'Golf', 'Ice Hockey', 'Skating', 'Cricket', 'Triathlon', 'Rackets', 'Croquet', 'Water Motorsports', 'Basque Pelota', 'Jeu de paume', 'Roque'] # Increase the width plt.figure(figsize=(15,4)) plt.bar(Sports,people_playing_the_sports) plt.xticks(rotation=90) plt.show()
Isn’t it a lot better now? Just changing the size of the graph has made such a huge impact and now we can understand the graph a lot better.
Changing the Height of the Graph using Matplotlib Figsize
Suppose we have created the same bar chart horizontally, the default height would look untidy, right? Let us see how we can increase the height of the graph.
import matplotlib.pyplot as plt people_playing_the_sports=[3828, 3448, 2523, 2214, 1547, 1387, 1325,1140,1105,1061,1025,1002,940,910,894,886,842,548,435,335,305,272,192,180,174,120,120,94,80,66,59,30,27, 27,24,18,10,8,5,4,3,3] sports_name=['Aquatics', 'Athletics', 'Rowing', 'Gymnastics', 'Fencing', 'Football','Hockey', 'Wrestling', 'Shooting', 'Sailing', 'Cycling','Canoe / Kayak', 'Basketball', 'Volleyball', 'Equestrian', 'Handball','Boxing', 'Weightlifting', 'Judo', 'Baseball', 'Archery', 'Tennis','Rugby', 'Softball', 'Modern Pentathlon', 'Table Tennis', 'Badminton','Tug of War', 'Taekwondo', 'Polo', 'Lacrosse', 'Golf', 'Ice Hockey', 'Skating', 'Cricket', 'Triathlon', 'Rackets', 'Croquet', 'Water Motorsports', 'Basque Pelota', 'Jeu de paume', 'Roque'] # Increase the width and the height plt.figure(figsize=(15,10)) plt.barh(Sports,people_playing_the_sports) plt.xticks(rotation=90) plt.show()
Explanation –
Firstly, we start by importing the matplotlib library. then we declared the players playing the sports and sports name in the list. Then by initializing the matplotlib figure by using a parameter of figsize, we can create a bigger-sized output. In our case, we’ve initialized it to 15 x 10 inches. As you can observe from the output, the data is widely spaced and it’s larger than the default dimensions.
Changing the figsize of the Matplotlib Subplots
We can also create subplots using matplotlib. In subplots, we create multiple subplots in a single figure. The more the number of subplots in a figure, the size of the subplot keeps changing. We can change the size of the figure and whatever size we give will be divided into subplots.
import matplotlib.pyplot as plt # make subplots with 2 rows and 1 column. # We If there were 3 rows, we would have done-fig, (ax1,ax2,ax3) fig, (ax1,ax2) = plt.subplots(nrows=2,ncols=1,figsize=(6,8)) y=[i*i for i in range(10)] #plotting for 1st subplot ax1.plot(range(10),y) #plotting for 2nd subplot ax2.bar(range(10),y)
Matplotlib Figsize Not Working Error
Sometimes, we may get an error- ‘matplotlib figsize not working’. This happens when we first plot the graph and then set the figsize.
import matplotlib.pyplot as plt technologies=['Data Science', 'Cyber Security', 'Web Development', 'Android Development', 'Data Analyst'] number_of_students=[78,49,112,129,59] # Wrong way- plt.bar(technologies,number_of_students) plt.figure(figsize=(10,5)) plt.xticks(rotation=90) plt.show() # Correct way plt.figure(figsize=(10,5)) plt.bar(technologies,number_of_students) plt.xticks(rotation=90) plt.show()
This is the common mistake that new programmers can do in using this method. Always remember that you can only set the figsize before the initialization of the graph. If the graph is already initialized, you cannot change the dimensions of the figure. Make sure that you place plt.figure() before your plt.bar() to avoid this error.
How to Set the Figure Size in Pixels
We can also set the figure size of the graph or chart according to the monitor, we can use dpi of our monitor to do so. You can detect the dpi of your monitor by search on the internet. There are multiple tools to do so.
# the dpi of my monitor is 120 my_dpi=120 # make a figure with the follwing figsize plt.figure(figsize=(400/my_dpi, 300/my_dpi), dpi=my_dpi) plt.bar([1,2,3,4,5],[5,4,3,2,1],align="center") plt.show()
Must Read:
- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python
Conclusion
We have seen that how changing the width and height can result in making the graph a lot better to understand and create insights. We can do this using the matplotlib figsize attribute of figure() function of the matplotlib library.
Try to run the programs on your side and let us know if you have any queries.
Happy Coding!
В визуализации данных график – это наиболее эффективный способ представления данных. Если его не описать в подробном виде, это может показаться сложным. Python имеет Matplotlib, который используется для представления данных в форме построения графиков.
Пользователь должен оптимизировать размер графика при его создании. В этом уроке мы обсудим различные методы изменения размера графика в Matplotlib по умолчанию в соответствии с требуемыми размерами пользователя или изменения размера данного графика.
Метод 1: используя set_figheight() и set_figwidth()
Пользователь может использовать set_figheight() для изменения высоты и set_figwidth() для изменения ширины графика.
Пример:
# first, import the matplotlib library import matplotlib.pyplot as plot # The values on x-axis x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The values on y-axis y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # Now, name the x and y axis plot.xlabel('X - AXIS') plot.ylabel('Y - AXIS') #Then, plot the line plot with its default size print("The plot is plotted in its default size: ") plot.plot(x_axis, y_axis) plot.show() # Now, plot the line plot after changing the size of its width and height K = plot.figure() K.set_figwidth(5) K.set_figheight(2) print("The plot is plotted after changing its size: ") plot.plot(x_axis, y_axis) plot.show()
Выход:
The plot is plotted in its default size:The plot is plotted after changing its size:
![]()
Метод 2: с помощью функции figsize()
Функция figsize() принимает два параметра, а именно ширину и высоту в дюймах. По умолчанию значения ширины = 6,4 дюйма и высоты = 4,8 дюйма.
Синтаксис:
Plot.figure(figsize =(x_axis, y_axis)
Где x_axis – ширина, а y_axis – высота в дюймах.
Пример:
# First, import the matplotlib library import matplotlib.pyplot as plot # The values on x-axis x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The values on y-axis y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] #Then, plot the line plot with its default size print("The plot is plotted in its default size: ") plot.plot(x_axis, y_axis) plot.show() # Now, plot the line plot after changing the size of figure to 3 X 3 plot.figure(figsize =(3, 3)) print("The plot is plotted after changing its size: ") plot.plot(x_axis, y_axis) plot.show()
Выход:
The plot is plotted in its default size:The plot is plotted after changing its size:
![]()
Метод 3: изменив rcParams по умолчанию
Пользователь может навсегда изменить размер фигуры по умолчанию в соответствии со своими потребностями, установив файл figure.figsize.
Пример:
# First, import the matplotlib library import matplotlib.pyplot as plot # The values on x-axis x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The values on y-axis y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # now, name the x axis plot.xlabel('X - AXIS') # name the y axis plot.ylabel('Y - AXIS') #Then, plot the line plot with its default size print("The plot is plotted in its default size: ") plot.plot(x_axis, y_axis) plot.show() # Now, change the rc parameters and plot the line plot after changing the size. plot.rcParams['figure.figsize'] = [3, 3] print("The plot is plotted after changing its size: ") plot.plot(x_axis, y_axis) plot.show() plot.scatter(x_axis, y_axis) plot.show()
Выход:
The plot is plotted in its default size:The plot is plotted after changing its size:
![]()
![]()
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
Today in this article we shall study resize the plots and subplots using Matplotlib. We all know that for Data Visualization purposes, Python is the best option. It has a set of modules that run on almost every system. So, in this small tutorial, our task is to brush up on the knowledge regarding the same. Let’s do this!
Basics of Plotting
Plotting basically means the formation of various graphical visualizations for a given data frame. There are various types in it:
- Bar plots: A 2D representation of each data item with respect to some entity on the x-y scale.
- Scatter plots: Plotting of small dots that represent data points on the x-y axis.
- Histogram
- Pie chart etc
There are various other techniques that are in use in data science and computing tasks.
To learn more about plotting, check this tutorial on plotting in Matplotlib.
What are subplots?
Subplotting is a distributive technique of data visualization where several plots are included in one diagram. This makes our presentation more beautiful and easy to understand the distribution of various data points along with distinct entities.
Read more about subplots in Matplotlib.
Python setup for plotting
- Programming environment: Python 3.8.5
- IDE: Jupyter notebooks
- Library/package: Matplotlib, Numpy
Create Plots to Resize in Matplotlib
Let’s jump to create a few plots that we can later resize.
Code:
from matplotlib import pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = 4 + 2*np.sin(2*x) fig, axs = plt.subplots() plt.xlabel("time") plt.ylabel("amplitude") plt.title("y = sin(x)") axs.plot(x, y, linewidth = 3.0) axs.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show()
Output:
This is just a simple plot for the sine wave that shows the amplitude movement when time increases linearly. Now, we shall see the subplots that make things more simple.
For a practice play, I am leaving codes for cos(x) and tan(x). See, if the code works or not.
Code for cos(x):
from matplotlib import pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = 4 + 2*np.cos(2*x) fig, axs = plt.subplots() plt.xlabel("time") plt.ylabel("amplitude") plt.title("y = cos(x)") axs.plot(x, y, linewidth = 3.0) axs.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show()
Output:
Code for tan(x):
from matplotlib import pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = 4 + 2*np.tan(2*x) fig, axs = plt.subplots() plt.xlabel("time") plt.ylabel("amplitude") plt.title("y = tan(x)") axs.plot(x, y, linewidth = 3.0) axs.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show()
Output:
The figures in Matplotlib are having a predefined size layout. So, when we need to change their size then the plot class has a figure function. This function is responsible for making the view more relative to the screen. The user has the full right to edit the dimensions of the plot. We shall understand this with an example:
Code:
import random from matplotlib import pyplot as plt plt.figure(figsize = (5, 5)) x = [] y = [] plt.xlabel("X values") plt.ylabel("Y values") plt.title("A simple graph") N = 50 for i in range(N): x.append(random.randint(0, 10)) y.append(random.randint(0, 10)) plt.bar(x, y, color = "pink") plt.show()
Output:
Explanation:
- In this code the first two lines of code import the pyplot and random libraries.
- In the second line of code, we use the figure() function. In that, the figsize parameter takes a tuple of the height and width of the plot layout.
- This helps us decide how much height we are giving.
- The random function inserts random values from ranges 1 to 10 in each of the two lists x, y.
- Then call the bar() function to create bar plots.
Resizing Plots in Matplotlib
This library is for creating subplots on a single axis or multiple axes. We can implement various bar plots on it. It helps to create common layouts for statistical data presentation.
Using figsize
Code example:
from matplotlib import pyplot as plt import numpy as np N = 5 menMeans = (20, 35, 30, 35, -27) womenMeans = (25, 32, 34, 20, -25) menStd = (2, 3, 4, 1, 2) womenStd = (3, 5, 2, 3, 3) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence fig, ax = plt.subplots(figsize = (6, 6)) p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men') p2 = ax.bar(ind, womenMeans, width, bottom=menMeans, yerr=womenStd, label='Women') ax.axhline(0, color='grey', linewidth=0.8) ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.legend() # Label with label_type 'center' instead of the default 'edge' ax.bar_label(p1, label_type='center') ax.bar_label(p2, label_type='center') ax.bar_label(p2) plt.show()
Output:
Explanation:
- The first two lines are import statements for modules.
- Then we define two tuples for men and women distribution values.
- To divide the graph the standard divisions are menStd and womenStd.
- Then the width of each bar is set to 0.35.
- We create two objects fig and ax of plt.subplot() function.
- This function has one parameter figsize. It takes a tuple of two elements depicting the resolution of the display image (width, height).
- Then we assign two variables p1 and p2 and call the bar() method using the ax instance.
- Then lastly just assign the labels to x-y axes and finally plot them.
Categorical plotting using subplots
The categorical data – information with labels plotting is also possible with matplotlib’s subplot. We can use the figsize
parameter here to divide the plots into many sections.
Example:
from matplotlib import pyplot as plt data = {'tiger': 10, 'giraffe': 15, 'lion': 5, 'deers': 20} names = list(data.keys()) values = list(data.values()) fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True) axs[0].bar(names, values) axs[1].scatter(names, values) axs[2].plot(names, values) fig.suptitle('Categorical Plotting of presence of all the animals in a zoo')
Output:
Explanation:
- At first, we create a dictionary of all the key-value pairs.
- Then we create a list of all the keys and a separate list of all the values.
- After that create a simple instance of the subplots() class.
- To write the necessary parameters, we give 1 at first to declare the number of rows. 3 to declare the number of columns. Thus, there are three plots on a single column
- Here, figsize is equal to (9, 3).
- Then we place each plot on the axes. Using the list functionality,
- ax[0] = bar graph
- ax[1] = scatter plot
- ax[2] = a simple line graph
- These show the presence of all the animals in a zoo.
Conclusion
So, here we learned how we can make things easier using subplots. Using the figsize parameter saves space and time for data visualization. So, I hope this is helpful. More to come on this topic. Till then keep coding.
Method 1: Specifying figsize
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(24, 12))
ax = plt.axes()
plt.sca(ax)
plt.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])
Note that the size gets applied in inches.
sca set the current axes.
Method 2: Using set_size_inches
import matplotlib.pyplot as plt
plt.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])
fig = plt.gcf()
fig.set_size_inches(24, 12)
gcf stands for get current figure
Method 3: Using rcParams
This can be used when you want to avoid using the figure environment. Please note that the rc settings are global to the matplotlib package and making changes here will affect all plots (future ones as well), until you restart the kernel.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (24,12)
plt.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])
Here as well, the sizes are in inches.
Seaborn
Method 1: Using matplotlib axes
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure(figsize=(24, 12))
ax = plt.axes()
sns.scatterplot(x =[1,2,3,4,5],y=[1,2,3,4,5], ax=ax)
This works for axes-level functions in Seaborn.
Method 2: Using rc
import seaborn as sns
sns.set(rc={'figure.figsize':(24,12)})
sns.scatterplot(x =[1,2,3,4,5],y=[1,2,3,4,5])
Again, this is a global setting and will affect all future plots, unless you restart the kernel.
Method 3: Using height and aspect ratio
This works for figure-level functions in seaborn.
import pandas as pd
import seaborn as sns
df = pd.read_csv('myfile.csv')
sns.pairplot(df,height = 12, aspect = 24/12)
Plotly
Method 1: Function Arguments in Plotly Express
import plotly.express as px
fig = px.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5], width=2400, height=1200)
fig.show()
Please note that instead of inches, the width and height are specified in pixels here.
Method 2: Using update_layout with Plotly Express
import plotly.express as px
fig = px.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])
fig.update_layout(
width=2400,
height=1200
)
fig.show()
Method 3: Using update_layout with Plotly Graph Objects
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1,2,3,4,5],
y=[1,2,3,4,5]
))
fig.update_layout(
width=2400,
height=1200)
fig.show()
If you are interested in data science and visualization using Python, you may find this course by Jose Portilla on Udemy to be very helpful. It has been the foundation course in Python for me and several of my colleagues.
You are also encouraged to check out further posts on Python on iotespresso.com.