Как сделать два графика рядом с помощью Python
Мой вопрос: что мне нужно изменить, чтобы иметь сюжеты бок о бок?
2 ответа
Измените настройки подзадачи на:
Параметрами для subplot являются: количество строк, количество столбцов и какая подзадача, в которой вы сейчас находитесь. Итак, 1, 2, 1 означает «1-строчный, 2-столбцовый рисунок: перейдите к первому подзаголовку». Затем 1, 2, 2 означает «1-строчный, 2-столбцовый рисунок: перейдите ко второму подзаголовку».
В настоящее время вы запрашиваете двухстрочный 1-столбцовый (то есть один поверх другого) макет. Вместо этого вам нужно запросить 1-строчный, 2-колонный макет. Когда вы это сделаете, результатом будет:
Чтобы свести к минимуму перекрытие подзаголовков, вам может понадобиться:
Creating multiple subplots using plt.subplots #
pyplot.subplots creates a figure and a grid of subplots with a single call, while providing reasonable control over how the individual plots are created. For more advanced use cases you can use GridSpec for a more general subplot layout or Figure.add_subplot for adding subplots at arbitrary locations within the figure.
A figure with just one subplot#
subplots() without arguments returns a Figure and a single Axes .
This is actually the simplest and recommended way of creating a single Figure and Axes.

Stacking subplots in one direction#
The first two optional arguments of pyplot.subplots define the number of rows and columns of the subplot grid.
When stacking in one direction only, the returned axs is a 1D numpy array containing the list of created Axes.

If you are creating just a few Axes, it’s handy to unpack them immediately to dedicated variables for each Axes. That way, we can use ax1 instead of the more verbose axs[0] .

To obtain side-by-side subplots, pass parameters 1, 2 for one row and two columns.

Stacking subplots in two directions#
When stacking in two directions, the returned axs is a 2D NumPy array.
If you have to set parameters for each subplot it’s handy to iterate over all subplots in a 2D grid using for ax in axs.flat: .
![Axis [0, 0], Axis [0, 1], Axis [1, 0], Axis [1, 1]](https://matplotlib.org/stable/_images/sphx_glr_subplots_demo_005.png,)
You can use tuple-unpacking also in 2D to assign all subplots to dedicated variables:

Sharing axes#
By default, each Axes is scaled individually. Thus, if the ranges are different the tick values of the subplots do not align.

You can use sharex or sharey to align the horizontal or vertical axis.

Setting sharex or sharey to True enables global sharing across the whole grid, i.e. also the y-axes of vertically stacked subplots have the same scale when using sharey=True .

For subplots that are sharing axes one set of tick labels is enough. Tick labels of inner Axes are automatically removed by sharex and sharey. Still there remains an unused empty space between the subplots.
To precisely control the positioning of the subplots, one can explicitly create a GridSpec with Figure.add_gridspec , and then call its subplots method. For example, we can reduce the height between vertical subplots using add_gridspec(hspace=0) .
label_outer is a handy method to remove labels and ticks from subplots that are not at the edge of the grid.

Apart from True and False , both sharex and sharey accept the values ‘row’ and ‘col’ to share the values only per row or column.

If you want a more complex sharing structure, you can first create the grid of axes with no sharing, and then call axes.Axes.sharex or axes.Axes.sharey to add sharing info a posteriori.

Polar axes#
The parameter subplot_kw of pyplot.subplots controls the subplot properties (see also Figure.add_subplot ). In particular, this can be used to create a grid of polar Axes.

Total running time of the script: ( 0 minutes 7.823 seconds)
Как расположить графики рядом python
Подскажите, пожалуйста, как расположить 2 график(рисунка) на одном поле(figure) последовательно один рядом с другим? Что-то вроде subplot(1, 2, 2), подробнее на картинке

Всё ещё ищете ответ? Посмотрите другие вопросы с метками python-3.x matplotlib или задайте свой вопрос.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.10.42345
How to plot in multiple subplots
How does the fig, axes work in this case? What does it do?
Also why wouldn’t this work to do the same thing:
![]()
13 Answers 13
There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example:

However, something like this will also work, it’s not so «clean» though since you are creating a figure with subplots and then add on top of them:

![]()

You can also unpack the axes in the subplots call
And set whether you want to share the x and y axes between the subplots

![]()
You might be interested in the fact that as of matplotlib version 2.1 the second code from the question works fine as well.
Figure class now has subplots method The Figure class now has a subplots() method which behaves the same as pyplot.subplots() but on an existing figure.
![]()
pyplot.subplots() returns a tuple fig, ax which is unpacked in two variables using the notation
does not work because subplots() is a function in pyplot not a member of the object Figure .