Matplotlib — одна из наиболее широко используемых библиотек визуализации данных в Python. Большая часть популярности Matplotlib связана с его параметрами настройки — вы можете настроить практически любой элемент из его иерархии объектов.
В этом уроке мы рассмотрим, как изменить размер фигуры в Matplotlib.
Создание сюжета
Сначала создадим простой график на фигуре:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Здесь мы построили синусоидальную функцию, начиная от 0
и до 10
с шагом 0.1
. Выполнение этого кода дает:
Объект Figure
, если явно не создан, создается по умолчанию и содержит все элементы, которые мы можем и не можем видеть. Изменение размера Figure
, в свою очередь, изменит размер наблюдаемых элементов.
Давайте посмотрим, как можно изменить размер фигуры.
Изменить размер рисунка в Matplotlib
Установите аргумент figsize
Во-первых, самый простой способ изменить размер фигуры — использовать аргумент figsize
. Вы можете использовать этот аргумент либо при инициализации Pyplot, либо в существующем объекте Figure
.
Давайте сначала изменим его во время инициализации:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.figure(figsize=(3, 3))
plt.plot(x, y)
plt.show()
Здесь мы получили доступ к экземпляру Figure
, который был создан по умолчанию, и передали аргумент figsize
. Обратите внимание, что размер определяется в дюймах, а не в пикселях. В результате получится фигура размером 3 на 3 дюйма:
Перед построением переменных важно установить размер фигуры.
Matplotlib / PyPlot в настоящее время не поддерживают размеры метрик, однако легко написать вспомогательную функцию для преобразования между ними:
def cm_to_inch(value):
return value/2.54
А затем отрегулируйте размер графика следующим образом:
plt.figure(figsize=(cm_to_inch(15),cm_to_inch(10)))
Это создаст участок размером 15 см на 10 см:
В качестве альтернативы, если вы создаете объект Figure
для своего сюжета, вы можете сразу назначить размер:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize=(8, 6))
# Adds subplot on position 1
ax = fig.add_subplot(121)
# Adds subplot on position 2
ax2 = fig.add_subplot(122)
ax.plot(x, y)
ax2.plot(x, z)
plt.show()
Здесь мы явно присвоили объекту возвращаемое значение функции figure()
. Затем мы можем добавить оси к этой фигуре, чтобы создать несколько подзаголовков и построить на них график.
Мы использовали функцию add_subplot()
, которая принимает ряд числовых значений. Первое число указывает, сколько строк вы хотите добавить к фигуре, второе число указывает, сколько столбцов вы хотите добавить, а третье число указывает номер графика, который вы хотите добавить.
Это означает, что если вы перейдете 111
в функцию add_subplots()
, к рисунку будет добавлен один новый подзаголовок. Между тем, если бы вы использовали числа 221
, полученный график имел бы четыре оси с двумя столбцами и двумя строками, а формируемый вами подзаголовок находится в 1-й позиции.
Этот код приводит к:
Установите высоту и ширину фигуры в Matplotlib
Вместо аргумента figsize
мы также можем установить высоту и ширину фигуры. Это можно сделать либо с помощью функции set()
с figheight
и figwidth
, или через функции set_figheight()
и set_figwidth()
.
Первый позволяет вам написать одну строку для нескольких аргументов, а второй предоставляет более читаемый код.
Пойдем со вторым вариантом:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)
# Adds subplot on position 1
ax = fig.add_subplot(121)
# Adds subplot on position 2
ax2 = fig.add_subplot(122)
ax.plot(x, y)
ax2.plot(x, z)
plt.show()
Этот код приводит к:
Наконец, вы также можете использовать эту функцию set_size_inches()
:
fig = plt.figure()
fig.set_size_inches(10, 5)
# Adds subplot on position 1
ax = fig.add_subplot(121)
# Adds subplot on position 2
ax2 = fig.add_subplot(122)
ax.plot(x, y)
ax2.plot(x, z)
plt.show()
И это работает так же, как установка аргумента figsize
или использование двух функций:
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
В визуализации данных график – это наиболее эффективный способ представления данных. Если его не описать в подробном виде, это может показаться сложным. 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 вместе с вами, читаю, собираю и записываю информацию опытных программистов.
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.
When creating plots using Matplotlib, you get a default figure size of 6.4 for the width and 4.8 for the height (in inches).
In this article, you’ll learn how to change the plot size using the following:
- The
figsize()
attribute. - The
set_figwidth()
method. - The
set_figheight()
method. - The
rcParams
parameter.
Let’s get started!
As stated in the previous section, the default parameters (in inches) for Matplotlib plots are 6.4 wide and 4.8 high. Here’s a code example:
import matplotlib.pyplot as plt
x = [2,4,6,8]
y = [10,3,20,4]
plt.plot(x,y)
plt.show()
In the code above, we first imported matplotlib
. We then created two lists — x
and y
— with values to be plotted.
Using plt.plot()
, we plotted list x
on the x-axis and list y
on the y-axis: plt.plot(x,y)
.
Lastly, the plt.show()
displays the plot. Here’s what the plot would look like with the default figure size parameters:
We can change the size of the plot above using the figsize()
attribute of the figure()
function.
The figsize()
attribute takes in two parameters — one for the width and the other for the height.
Here’s what the syntax looks like:
figure(figsize=(WIDTH_SIZE,HEIGHT_SIZE))
Here’s a code example:
import matplotlib.pyplot as plt
x = [2,4,6,8]
y = [10,3,20,4]
plt.figure(figsize=(10,6))
plt.plot(x,y)
plt.show()
We’ve added one new line of code: plt.figure(figsize=(10,6))
. This will modify/change the width and height of the plot.
Here’s what the plot would look like:
How to Change Plot Width in Matplotlib with set_figwidth()
You can use the set_figwidth()
method to change the width of a plot.
We’ll pass in the value the width should be changed to as a parameter to the method.
This method will not change the default or preset value of the plot’s height.
Here’s a code example:
import matplotlib.pyplot as plt
x = [2,4,6,8]
y = [10,3,20,4]
plt.figure().set_figwidth(15)
plt.plot(x,y)
plt.show()
Using the set_figwidth()
method, we set the width of the plot to 10. Here’s what the plot would look like:
How to Change Plot Height in Matplotlib with set_figheight()
You can use the set_figheight()
method to change the height of a plot.
This method will not change the default or preset value of the plot’s width.
Here’s a code example:
import matplotlib.pyplot as plt
x = [2,4,6,8]
y = [10,3,20,4]
plt.figure().set_figheight(2)
plt.plot(x,y)
plt.show()
Using the set_figheight()
in the example above, we set the plot’s height to 2. Here’s what the plot would look like:
How to Change Default Plot Size in Matplotlib with rcParams
You can override the default plot size in Matplotlib using the rcParams
parameter.
This is useful when you want all your plots to follow a particular size. This means you don’t have to change the size of every plot you create.
Here’s an example with two plots:
import matplotlib.pyplot as plt
x = [2,4,6,8]
y = [10,3,20,4]
plt.rcParams['figure.figsize'] = [4, 4]
plt.plot(x,y)
plt.show()
a = [5,10,15,20]
b = [10,20,30,40]
plt.plot(a,b)
Using the figure.figsize
parameter, we set the default width and height to 4: plt.rcParams['figure.figsize'] = [4, 4]
. These parameters will change the default width and height of the two plots.
Here are the plots:
Summary
In this article, we talked about the different ways you can change the size of a plot in Matplotlib.
We saw code examples and visual representation of the plots. This helped us understand how each method can be used to change the size of a plot.
We discussed the following methods used in changing the plot size in Matplotlib:
- The
figsize()
attribute can be used when you want to change the default size of a specific plot. - The
set_figwidth()
method can be used to change only the width of a plot. - The
set_figheight()
method can be used to change only the height of a plot. - The
rcParams
parameter can be used when want to override the default plot size for all your plots. Unlike the thefigsize()
attribute that targets a specific plot, thercParams
parameter targets all the plots in a project.
Happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Introduction
Matplotlib is one of the most widely used data visualization libraries in Python. Much of Matplotlib’s popularity comes from its customization options — you can tweak just about any element from its hierarchy of objects.
In this tutorial, we’ll take a look at how to change a figure size in Matplotlib.
Creating a Plot
Let’s first create a simple plot in a figure:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Here, we’ve plotted a sine function, starting at 0
and ending at 10
with a step of 0.1
. Running this code yields:
The Figure
object, if not explicitly created, is created by default and contains all the elements we can and cannot see. Changing the size of the Figure
will in turn change the size of the observable elements too.
Let’s take a look at how we can change the figure size.
Change Figure Size in Matplotlib
Set the figsize Argument
First off, the easiest way to change the size of a figure is to use the figsize
argument. You can use this argument either in Pyplot’s initialization or on an existing Figure
object.
Let’s first modify it during initialization:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.figure(figsize=(3, 3))
plt.plot(x, y)
plt.show()
Here, we’ve accessed the Figure
instance that was created by default and passed the figsize
argument. Note that the size is defined in inches, not pixels. This will result in a figure that’s 3in by 3in in size:
Matplotlib/PyPlot don’t currently support metric sizes, though, it’s easy to write a helper function to convert between the two:
def cm_to_inch(value):
return value/2.54
And then adjust the size of the plot like this:
plt.figure(figsize=(cm_to_inch(15),cm_to_inch(10)))
This would create a plot with the size of 15cm by 10cm:
Alternatively, if you’re creating a Figure
object for your plot, you can assign the size at that time:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize=(8, 6))
# Adds subplot on position 1
ax = fig.add_subplot(121)
# Adds subplot on position 2
ax2 = fig.add_subplot(122)
ax.plot(x, y)
ax2.plot(x, z)
plt.show()
Here, we’ve explicitly assigned the return value of the figure()
function to a Figure
object. Then, we can add axes to this figure to create multiple subplots and plot on them.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
We’ve used the add_subplot()
function, which accepts a series of numerical values. The first number specifies how many rows you want to add to the figure, the second number specifies how many columns you want to add, and the third number specifies the number of the plot that you want to add.
This means that if you in passed in 111
into the add_subplots()
function, one new subplot would be added to the figure. Meanwhile, if you used the numbers 221
, the resulting plot would have four axes with two columns and two rows — and the subplot you’re forming is in the 1st position.
This code results in:
Set the Height and Width of a Figure in Matplotlib
Instead of the figsize
argument, we can also set the height and width of a figure. These can be done either via the set()
function with the figheight
and figwidth
argument, or via the set_figheight()
and set_figwidth()
functions.
The former allows you to write one line for multiple arguments while the latter provides you with code that’s more readable.
Let’s go with the second option:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)
# Adds subplot on position 1
ax = fig.add_subplot(121)
# Adds subplot on position 2
ax2 = fig.add_subplot(122)
ax.plot(x, y)
ax2.plot(x, z)
plt.show()
This code results in:
Finally, you can also use the set_size_inches()
function as well:
fig = plt.figure()
fig.set_size_inches(10, 5)
# Adds subplot on position 1
ax = fig.add_subplot(121)
# Adds subplot on position 2
ax2 = fig.add_subplot(122)
ax.plot(x, y)
ax2.plot(x, z)
plt.show()
And this performs the same as setting the figsize
argument or using the two functions:
Conclusion
In this tutorial, we’ve gone over several ways to change the size of a figure in Matplotlib.
If you’re interested in Data Visualization and don’t know where to start, make sure to check out our book on Data Visualization in Python.
If you’re interested in Data Visualization and don’t know where to start, make sure to check out our bundle of books on Data Visualization in Python:
Data Visualization in Python with Matplotlib and Pandas is a book designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and allow them to build a strong foundation for advanced work with theses libraries — from simple plots to animated 3D plots with interactive buttons.
It serves as an in-depth, guide that’ll teach you everything you need to know about Pandas and Matplotlib, including how to construct plot types that aren’t built into the library itself.
Data Visualization in Python, a book for beginner to intermediate Python developers, guides you through simple data manipulation with Pandas, cover core plotting libraries like Matplotlib and Seaborn, and show you how to take advantage of declarative and experimental libraries like Altair. More specifically, over the span of 11 chapters this book covers 9 Python libraries: Pandas, Matplotlib, Seaborn, Bokeh, Altair, Plotly, GGPlot, GeoPandas, and VisPy.
It serves as a unique, practical guide to Data Visualization, in a plethora of tools you might use in your career.