Как наложить два графика друг на друга python
Перейти к содержимому

Как наложить два графика друг на друга python

  • автор:

Построение с Matplotlib

Добавление дополнительных функций к простому графику: метки оси, заголовок, метки оси, сетка и легенда

В этом примере мы берем график с синусоидой и добавляем к нему больше функций; а именно заголовок, метки оси, заголовок, метки оси, сетка и легенда.

Создание нескольких графиков на одной фигуре путем наложения, аналогичного MATLAB

В этом примере кривая синуса и кривая косинуса изображены на одном рисунке путем наложения графиков друг на друга.

Создание нескольких графиков на одном рисунке с использованием наложения графиков с отдельными командами графиков

Как и в предыдущем примере, здесь кривая синуса и косинуса строится на одном и том же рисунке с использованием отдельных команд построения. Это более Pythonic и может быть использовано для получения отдельных маркеров для каждого сюжета.

Графики с общей осью X, но с другой осью Y: с использованием twinx ()

В этом примере мы построим синусоидальную и гиперболическую синусоидальные кривые на одном графике с общей осью X, имеющей разные оси Y. Это достигается за счет использования команды TwinX ().

Графики с общей осью Y и другой осью X с использованием twiny ()

В этом примере, график с кривыми , имеющими общую ось ординат , но разные оси х продемонстрирована с использованием метода twiny (). Кроме того, некоторые дополнительные функции, такие как заголовок, легенда, метки, сетки, метки осей и цвета, добавляются к графику.

Seaborn Multiple Plots Subplotting with matplotlib and seaborn

In this micro tutorial we will learn how to create subplots using matplotlib and seaborn.

Import all Python libraries needed

Exit fullscreen mode

Create the DataFrame

We are using the Pokemon with stats dataset from Kaggle.

The cell below import the dataset file and create the pokemon pandas DataFrame. So use show the 4 first rows using pd.DataFrame.head function.

Exit fullscreen mode

Alt Text

Plotting (and subplotting) samples

As we can see in the matplotlib documentation (references at the end of file), subplots() without arguments returns a Figure and a single Axes, which we can unpack using the syntax bellow.

Exit fullscreen mode

Alt Text

Thus, we can give two arguments to subplots functions: nrows and ncols . If given in that order, we don’t need to type the arg names, just its values. In our example we create a plot with 1 row and 2 columns, still no data passed.

Exit fullscreen mode

Alt Text

Now axes is an array of AxesSubplot, so we can access each ax separetely and set a different title, for instance.

  • figsize set the total dimension of our figure
  • sharex and sharey are used to share one or both axes between the charts (needed data to work)

Exit fullscreen mode

Alt Text

Exit fullscreen mode

Alt Text

Using data

We select three Pokemon to use in the next example. The three initial Pokemon of 1st Generation: Bulbasaur, Charmander and Squirtle.

Exit fullscreen mode

Then, we create a plot with 3 subplots in a 1 row x 3 columns figure.

We use sns.barplot where we need to set the a argument with the correspondent element from axes variable.

Exit fullscreen mode

Alt Text

Final example

And a final example plottin a 2 rows X 3 columns plot showing Pokemon stats by Generation.

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.

A single plot

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.

Vertically stacked subplots

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] .

Vertically stacked subplots

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

Horizontally stacked subplots

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]

You can use tuple-unpacking also in 2D to assign all subplots to dedicated variables:

Sharing x per column, y per row

Sharing axes#

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

Axes values are scaled individually by default

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

Aligning x-axis using sharex

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 .

Sharing both axes

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.

Sharing both axes

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

Sharing x per column, y per row

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.

main, unrelated, shares x with main, also unrelated

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.

subplots demo

Total running time of the script: ( 0 minutes 7.823 seconds)

How can I overlay two graphs in Seaborn?

How can I overlay two graphs in Seaborn? I have two columns in my data I would like to have them in the same graph. How can I do it preserving the labeling for both graphs.

3 Answers 3

seaborn function that operate on a single Axes can take one as an argument.

For instance, the docs to seaborn.kdeplot include:

You could then do:

One solution is to introduce a secondary axis:

enter image description here

petezurich's user avatar

The data is about Private vs Public collage data but works, as we can see we load all the global parameters to a seaborn object and later we map the charts to the same pane.

Amir's user avatar

Omar Villa's user avatar

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.8.43486

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *