Python plt figure figsize

Изменить размер рисунка в Matplotlib

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() , которая принимает ряд числовых значений. Первое число указывает, сколько строк вы хотите добавить к фигуре, второе число указывает, сколько столбцов вы хотите добавить, а третье число указывает номер графика, который вы хотите добавить.

Читайте также:  Can write method in java

Это означает, что если вы перейдете 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 или использование двух функций:

Источник

matplotlib.pyplot.figure#

If a figure with that identifier already exists, this figure is made active and returned. An integer refers to the Figure.number attribute, a string refers to the figure label.

If there is no figure with the identifier or num is not given, a new figure is created, made active and returned. If num is an int, it will be used for the Figure.number attribute, otherwise, an auto-generated integer value is used (starting at 1 and incremented for each new figure). If num is a string, the figure label and the window title is set to this value. If num is a SubFigure , its parent Figure is activated.

figsize (float, float), default: rcParams[«figure.figsize»] (default: [6.4, 4.8] )

dpi float, default: rcParams[«figure.dpi»] (default: 100.0 )

The resolution of the figure in dots-per-inch.

facecolor color, default: rcParams[«figure.facecolor»] (default: ‘white’ )

edgecolor color, default: rcParams[«figure.edgecolor»] (default: ‘white’ )

frameon bool, default: True

If False, suppress drawing the figure frame.

FigureClass subclass of Figure

If set, an instance of this subclass will be created, rather than a plain Figure .

clear bool, default: False

If True and the figure already exists, then it is cleared.

The layout mechanism for positioning of plot elements to avoid overlapping Axes decorations (labels, ticks, etc). Note that layout managers can measurably slow down figure display.

  • ‘constrained’: The constrained layout solver adjusts axes sizes to avoid overlapping axes decorations. Can handle complex plot layouts and colorbars, and is thus recommended. See Constrained Layout Guide for examples.
  • ‘compressed’: uses the same algorithm as ‘constrained’, but removes extra space between fixed-aspect-ratio Axes. Best for simple grids of axes.
  • ‘tight’: Use the tight layout mechanism. This is a relatively simple algorithm that adjusts the subplot parameters so that decorations do not overlap. See Figure.set_tight_layout for further details.
  • ‘none’: Do not use a layout engine.
  • A LayoutEngine instance. Builtin layout classes are ConstrainedLayoutEngine and TightLayoutEngine , more easily accessible by ‘constrained’ and ‘tight’. Passing an instance allows third parties to provide their own layout engine.
Читайте также:  Оператор if else питон

If not given, fall back to using the parameters tight_layout and constrained_layout, including their config defaults rcParams[«figure.autolayout»] (default: False ) and rcParams[«figure.constrained_layout.use»] (default: False ).

Additional keyword arguments are passed to the Figure constructor.

A newly created figure is passed to the new_manager method or the new_figure_manager function provided by the current backend, which install a canvas and a manager on the figure.

Once this is done, rcParams[«figure.hooks»] (default: [] ) are called, one at a time, on the figure; these hooks allow arbitrary customization of the figure (e.g., attaching callbacks) or of associated elements (e.g., modifying the toolbar). See mplcvd — an example of figure hook for an example of toolbar customization.

If you are creating many figures, make sure you explicitly call pyplot.close on the figures you are not using, because this will enable pyplot to properly clean up the memory.

rcParams defines the default values, which can be modified in the matplotlibrc file.

Источник

Matplotlib Figure Size – How to Change Plot Size in Python with plt.figsize()

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Matplotlib Figure Size – How to Change Plot Size in Python with plt.figsize()

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.

How to Change Plot Size in Matplotlib with plt.figsize()

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:

matplotlib

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.

Читайте также:  Collection order by java

Here’s what the syntax looks like:

figure(figsize=(WIDTH_SIZE,HEIGHT_SIZE))
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:

matplotlib1

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.

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:

matplotlib2

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.

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:

matplotlib3

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.

matplotlib4matplotlib5-1

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 the figsize() attribute that targets a specific plot, the rcParams parameter targets all the plots in a project.

Источник

Оцените статью