Python matplotlib new figure

Create pyplot figure with matplotlib [In-Depth Tutorial]

matplotlib.pyplot is a sub-library of Python’s matplotlib library that provides convenient ways to create static, animated, and interactive visualizations in Python. The pyplot module provides a procedural interface to the object-oriented plotting library matplotlib. This is closely related to Matlab’s plotting functions.

The figure() function in pyplot creates a new figure and assigns it a number. By default, figures are created with a default size and resolution, but these can be changed with the figsize and dpi arguments respectively.

Once a character is created, you can add data to it using various functions such as plot() , scatter() , hist() , etc. You can also add labels and titles to axes and entire figures using functions such as xlabel() , ylabel() , and title() . You can also customize the appearance of your figure using functions such as xlim() , ylim() , and grid() , legend() , etc.

Additionally, you can create multiple plots in a single figure using the subplots() function. You can also adjust the spacing between plots using subplots_adjust() .

Using matplotlib.pyplot library to create figures and plots

You can use the figure() function to create a new figure and assign it to a variable. Then you can use various functions such as plot() , scatter() , and hist() to add data to the figure. You can also use xlabel() , ylabel() , and title() to add labels to the x-axis, y-axis, and overall title of the plot, respectively. Additionally, you can use xlim() and ylim() to set the limits of the x-axis and y-axis, respectively.

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] # Create a figure and axes fig, ax = plt.subplots() # Plot the data ax.plot(x, y) # Set the x and y axis labels ax.set_xlabel("X-axis") ax.set_ylabel("Y-axis") # Show the plot plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-1: Create Line Plot

This creates a simple line plot of the x and y values. The plot() function is used to create the line plot and the xlabel() , ylabel() , and title() functions are used to add labels to the x-axis, y-axis, and overall title of the plot, respectively.

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] plt.plot(x, y) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Line Plot') plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-2: Create Scatter Plot

This creates a scatter plot of the x and y values. The scatter() function is used to create the scatter plot and the xlabel() , ylabel() , and title() functions are used to add labels to the x-axis, y-axis, and overall title of the plot, respectively.

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] plt.scatter(x, y) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Scatter Plot') plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-3: Create Bar Plot

This creates a bar plot of the x and y values. The bar() function is used to create the bar plot and the xlabel() , ylabel() , and title() functions are used to add labels to the x-axis, y-axis, and overall title of the plot, respectively.

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] plt.bar(x, y) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Bar Plot') plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-4: Create Multiple plots in a single figure

This creates a 2×2 grid of plots, with a line plot, scatter plot, bar plot, and histogram in each of the four subplots. The subplots() function is used to create the multiple plots and the plot() , scatter() , bar() , and hist() functions are used to add data to each of the subplots, respectively.

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 1].scatter(x, y) axs[1, 0].bar(x, y) axs[1, 1].hist(y) plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-5: Define figsize with figure() function

In matplotlib.pyplot , the figure() function creates a new figure and assigns it a number. By default, the figure will be created with the default size and resolution, but you can modify these using the figsize and dpi arguments respectively.

figsize argument is a tuple of width, height in inches and dpi argument is the resolution of the figure in dots per inches.

Here is an example of how to use the figsize argument to create a figure with a specific size:

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [2, 4, 6, 8] fig = plt.figure(figsize=(4, 3)) plt.plot(x, y) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Line Plot') plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-6: Add title to pyplot figures

In matplotlib, the pyplot module provides a simple way to create and manipulate figures and plots. To add a title to a figure, you can use the title() function, which takes a string argument for the title text.

import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.title("My Figure Title") plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-7: Using add_subplot() with pypot module

In matplotlib, the pyplot module’s add_subplot() function can be used to add one or more subplots to a figure. The basic syntax for add_subplot() is:

add_subplot(nrows, ncols, plot_number)

Where nrows and ncols are the number of rows and columns of subplots in the figure, and plot_number is the subplot that you want to create, counting from the left to right and top to bottom.

import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) plt.show()

This will create a 2×2 grid of subplots and return the subplot objects as ax1 , ax2 , and ax3 . You can then use these subplot objects to plot data, set labels, etc.

Create pyplot figure with matplotlib [In-Depth Tutorial]

You can also use the subplots() function to create multiple subplots in one step.

fig, axs = plt.subplots(nrows, ncols)
nrows = 2 ncols = 2 fig, axs = plt.subplots(nrows, ncols)

This will create a figure with a 2×2 grid of subplots.

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-8: Change background color of pyplot figure

In matplotlib, we can change the background color of a figure is by using the set_facecolor() method of the figure object. This method takes a string argument for the color, which can be specified in a variety of ways, such as by its name (e.g., «white»), by its RGB value (e.g., (1, 1, 1) for white), or by its hex code (e.g., » #FFFFFF » for white).

import matplotlib.pyplot as plt fig = plt.figure() fig.set_facecolor('lightblue') plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

Example-9: Modify the axis limit of pyplot figure

In matplotlib, the pyplot module provides several ways to manipulate the axis of a figure.

One way to control the axis of a figure is by using the xlim() and ylim() functions, which can be used to set the limits of the x and y axis, respectively. For example:

import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.xlim(0, 5) plt.ylim(0, 5) plt.show()

Create pyplot figure with matplotlib [In-Depth Tutorial]

We can also control the axis of a figure by using the gca() function (get current axis) which returns the current axis of the figure and allows to apply methods to it. For example:

import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) ax = plt.gca() ax.set_xticks([0, 1, 2, 3, 4]) ax.set_yticks([0, 1, 2, 3, 4]) plt.show()

This will create a simple line plot and set the x-axis ticks to [0, 1, 2, 3, 4] and y-axis ticks to [0, 1, 2, 3, 4] .

In case of subplots, these functions can be applied to individual subplots by passing the subplot object as an argument. For example:

fig, axs = plt.subplots(nrows, ncols) axs[0,0].set_xlim(0,5)

This will set the x-axis limit of the first subplot (top left) to range from 0 to 5.

Источник

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

Источник

Читайте также:  Min width в php
Оцените статью