Python matplotlib several plots

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.

import matplotlib.pyplot as plt import numpy as np # Some example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) 

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.

fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('A single plot') 

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.

Читайте также:  Алгоритмы обработки изображений python

When stacking in one direction only, the returned axs is a 1D numpy array containing the list of created Axes.

fig, axs = plt.subplots(2) fig.suptitle('Vertically stacked subplots') axs[0].plot(x, y) axs[1].plot(x, -y) 

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

fig, (ax1, ax2) = plt.subplots(2) fig.suptitle('Vertically stacked subplots') ax1.plot(x, y) ax2.plot(x, -y) 

Vertically stacked subplots

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

fig, (ax1, ax2) = plt.subplots(1, 2) fig.suptitle('Horizontally stacked subplots') ax1.plot(x, y) ax2.plot(x, -y) 

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

fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].set_title('Axis [0, 0]') axs[0, 1].plot(x, y, 'tab:orange') axs[0, 1].set_title('Axis [0, 1]') axs[1, 0].plot(x, -y, 'tab:green') axs[1, 0].set_title('Axis [1, 0]') axs[1, 1].plot(x, -y, 'tab:red') axs[1, 1].set_title('Axis [1, 1]') for ax in axs.flat: ax.set(xlabel='x-label', ylabel='y-label') # Hide x labels and tick labels for top plots and y ticks for right plots. for ax in axs.flat: ax.label_outer() 

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:

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) fig.suptitle('Sharing x per column, y per row') ax1.plot(x, y) ax2.plot(x, y**2, 'tab:orange') ax3.plot(x, -y, 'tab:green') ax4.plot(x, -y**2, 'tab:red') for ax in fig.get_axes(): ax.label_outer() 

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.

fig, (ax1, ax2) = plt.subplots(2) fig.suptitle('Axes values are scaled individually by default') ax1.plot(x, y) ax2.plot(x + 1, -y) 

Axes values are scaled individually by default

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

fig, (ax1, ax2) = plt.subplots(2, sharex=True) fig.suptitle('Aligning x-axis using sharex') ax1.plot(x, y) ax2.plot(x + 1, -y) 

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 .

fig, axs = plt.subplots(3, sharex=True, sharey=True) fig.suptitle('Sharing both axes') axs[0].plot(x, y ** 2) axs[1].plot(x, 0.3 * y, 'o') axs[2].plot(x, y, '+') 

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.

fig = plt.figure() gs = fig.add_gridspec(3, hspace=0) axs = gs.subplots(sharex=True, sharey=True) fig.suptitle('Sharing both axes') axs[0].plot(x, y ** 2) axs[1].plot(x, 0.3 * y, 'o') axs[2].plot(x, y, '+') # Hide x labels and tick labels for all but bottom plot. for ax in axs: ax.label_outer() 

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.

fig = plt.figure() gs = fig.add_gridspec(2, 2, hspace=0, wspace=0) (ax1, ax2), (ax3, ax4) = gs.subplots(sharex='col', sharey='row') fig.suptitle('Sharing x per column, y per row') ax1.plot(x, y) ax2.plot(x, y**2, 'tab:orange') ax3.plot(x + 1, -y, 'tab:green') ax4.plot(x + 2, -y**2, 'tab:red') for ax in fig.get_axes(): ax.label_outer() 

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.

fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].set_title("main") axs[1, 0].plot(x, y**2) axs[1, 0].set_title("shares x with main") axs[1, 0].sharex(axs[0, 0]) axs[0, 1].plot(x + 1, y + 1) axs[0, 1].set_title("unrelated") axs[1, 1].plot(x + 2, y + 2) axs[1, 1].set_title("also unrelated") fig.tight_layout() 

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.

fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar')) ax1.plot(x, y) ax2.plot(x, y ** 2) plt.show() 

subplots demo

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

Источник

How to Plot Multiple Graphs in Python?

Jerri De La Cruz

How to Plot Multiple Graphs in Python?

Python is a programming language with many features. It is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.

Python is a versatile language when it comes to visualization. There are many libraries in the Python ecosystem that can be used to create static, animated, and interactive visualizations.

In this post, we will see how to use some of these Python visualization libraries in practice. We will take a look at how to create static and animated visualizations using the Matplotlib and seaborn libraries.

How to Create Multiple Matplotlib plots in one Figure

The purpose of the subplot() function in the Matplotlib library of python is to provide a way for the programmer to display multiple graphs within a single plot. In the following paragraphs, we will take a closer look at this function and how it can be used.

matplotlib.pyplot.subplots(numrows, numcols, plot_number) 

To plot multiple graphs on one plot, follow these steps.

1. Install and import the matplotlib and NumPy library. Matplotlib library is used to plot graphs in python, and NumPy deals with all mathematical operations.

import matplotlib.pyplot as plt import NumPy as np

2. Create an array of time using the np.arange() function of NumPy.

Here 0 is the start point, 5 is the endpoint, and 0.2 is the intervention between 0 and 5 (both inclusive).

3. Now plot the graph one as

plt.subplot(121) plt.plot(t, ‘r- -’) plt.xlabel(‘Plot 1)

4. Similarly, plot graph 2 as …

plt.subplot(122) plt.plot(t, ‘r- -’, t**2, ‘b*’, t**3, ‘g-o’) plt.xlabel(‘Plot 2)

5. Now show both the graph in one plot as…

plt. subtitle("Plotting multiple Graphs") plt.show()

Full Syntax

import matplotlib.pyplot as plt import numpy as np t=np.arange(0, 5, 0.2) plt.subplot(121) plt.plot(t, "r--") plt.xlabel("Graph 1") plt.subplot(122) plt.plot(t, "r--", t**2, "b+", t**3, "g-o") plt.xlabel("Graph 1") plt.suptitle("Plotting Multiple Graphs") plt.show()

Explanation

  • The purpose of importing matplotlib and NumPy is so that matplotlib can plot the graphs and NumPy can set the time for when the graphs are plotted.
  • Then we utilize the subplot() function. The subplot function assists in plotting two different graphs in one figure.
  • Here in this code example subplot() function has parameters 121 and 122; here, 1 defines the number of rows, and 2 defines the number of columns, as we discussed in the syntax of the subplot function. The 3rd parameter defines which one is which plot number, so 1 defines the 1st plot no, and 2 defines the 2nd plot no.
  • Then we are using the plot function inside which we are passing t, which is defined as time and the plot design.

here ‘r- -’ means:
r = red color
– – (double dash) = these are the patterns that are going to be printed on screen (See the output image)

How to plot multiple graphs in python on the same plot

We have previously learned how to plot multiple graphs using the subplot() function of the matplotlib library. Now, we will explore how to plot multiple graphs in one plot by superimposing them. We can do this by directly plotting the graphs one by one.

For an example, see the code below.

import matplotlib.pyplot as plt import numpy as np t=np.arange(0, 5, 0.2) plt.plot(t, "r--") plt.plot(t**2, "g*") plt.xlabel("Time") plt.suptitle("Superimposing both graphs in one") plt.show()

Output

Explanation
As we can see, we are plotting the graphs one by one, and all the graphs can be seen in a single plot. This is another method in which we are superimposing the other graphs into one.

How to plot multiple graphs in one figure legend in python

What is a legend?

Legends are key in understanding graphs. They provide context for the different areas of the graph. Without a legend, a graph would be difficult to interpret.

A lot of time graph can be self-explanatory but having a title in the graph labels on the axis and a legend that explains more about the graph. This section will learn how to insert a legend into the plot. Basically legend function can be in three forms.

  1. Legend without labels and handles
  2. Legend with labels only
  3. Legend with both labels and handles

Legend without labels and handles

import numpy as np import matplotlib.pyplot as plt t = np.array([1,2,3,4]) plt.plot(t**2,t, color='red',label='squares') plt.plot(t**3,t, color='green',label='cubes') plt.title("Squares and Cubes") plt.legend() plt.show()

Explanation
The labels included in the plot function will be automatically detected by the legend function if no argument is mentioned. Therefore, if you want the legend to work, you must make sure to include labels in the plot function.

The legend function displays all plots that have been labeled with keyword labels, and they are in the same order as when they were plotted.

Legend with labels only

We can choose not to label our plot as we are plotting by ignoring labels inside the plot function. However, we can add labels by passing them into the legend function after the plots have been plotted.

import numpy as np import matplotlib.pyplot as plt t = np.array([1,2,3,4]) plt.plot(t**2,t, color='red') plt.plot(t**3,t, color='green') plt.title("Squares and Cubes") plt.legend([“squares”, “cubes”]) plt.show() 

Output

Note: Make sure this order is crucial while manually writing the labels inside the legend. You must have ordered your label as same as the plots are plotted.

Legend with labels and handles

import numpy as np import matplotlib.pyplot as plt t = np.array([1,2,3,4]) list1, = plt.plot(t**2,t, color='red') list2, = plt.plot(t**3,t, color='green') plt.title("Squares and Cubes") plt.legend([list1, list2],["squares","cubes"]) plt.show()

Output

Explanation
Here plot function will return a list of a single item, and we are taking that list item in variable list1 and list2 to unpack the list we are using comma(,). After that inside legend, we pass handles that are list names and then labels for that handles.

Learnt Math Tutor Allison teaches multiplication.

Learnt Math Tutor Allison teaches multiplication.

Learnt Public Health Tutor Carissa Teaches Yoga

Learnt Public Health Tutor Carissa Teaches Yoga

See more

Learnt Math Tutor Katherine P Teaches How to Find The Volume Of A Sphere

Learnt Math Tutor Katherine P Teaches How to Find The Volume Of A Sphere

What is a Run-on Sentence & How Do I Fix It?

What is a Run-on Sentence & How Do I Fix It?

What is a Statistical Question?

What is a Statistical Question?

How to Make Flashcards: Practical Advice for Better Studying

How to Make Flashcards: Practical Advice for Better Studying

Subscribe to new posts

Processing your application Please check your inbox and click the link to confirm your subscription There was an error sending the email

Find study guides, instructional videos, and tutors available to meet instantly online.

Источник

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