|
| 1 | +--- |
| 2 | +Title: '.figure()' |
| 3 | +Description: 'Creates a new figure window or activates an existing one for plotting.' |
| 4 | +Subjects: |
| 5 | + - 'Data Science' |
| 6 | + - 'Data Visualization' |
| 7 | +Tags: |
| 8 | + - 'Charts' |
| 9 | + - 'Graphs' |
| 10 | + - 'Matplotlib' |
| 11 | +CatalogContent: |
| 12 | + - 'learn-python-3' |
| 13 | + - 'paths/data-science' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`.figure()`** function in Matplotlib creates a new top-level container, called a figure, which acts as the canvas for all plots and axes in Matplotlib. If a figure with the given identifier already exists, it makes that figure active instead. |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```pseudo |
| 21 | +matplotlib.pyplot.figure( |
| 22 | + num=None, |
| 23 | + figsize=None, |
| 24 | + dpi=None, |
| 25 | + facecolor=None, |
| 26 | + edgecolor=None, |
| 27 | + frameon=True, |
| 28 | + FigureClass=<class 'matplotlib.figure.Figure'>, |
| 29 | + clear=False, |
| 30 | + **kwargs |
| 31 | +) |
| 32 | +``` |
| 33 | + |
| 34 | +**Parameters:** |
| 35 | + |
| 36 | +- `num` (int or str, optional): Identifier for the figure. If the number or name already exists, that figure becomes active; otherwise, a new one is created. |
| 37 | +- `figsize` (tuple, optional): Width and height of the figure in inches, e.g. `(8, 6)`. |
| 38 | +- `dpi` (float, optional): Dots per inch; controls the resolution of the figure. |
| 39 | +- `facecolor` (color, optional): Background color of the figure. |
| 40 | +- `edgecolor` (color, optional): Border color of the figure. |
| 41 | +- `frameon` (bool, default: True): Whether to draw the figure frame. |
| 42 | +- `FigureClass` (`Figure` subclass, optional): The class used to create the figure instance. Defaults to `matplotlib.figure.Figure`. |
| 43 | +- `clear` (bool, default: False): If `True`, clears the existing figure before reusing it. |
| 44 | +- `**kwargs`: Additional parameters passed to the `Figure` constructor. |
| 45 | + |
| 46 | +**Return value:** |
| 47 | + |
| 48 | +Returns a `Figure` object, which is the main container that holds all plot elements like axes, titles, labels, and legends. |
| 49 | + |
| 50 | +## Example |
| 51 | + |
| 52 | +This example creates a new figure canvas with a specific size and background color, then adds a simple sine wave plot to it: |
| 53 | + |
| 54 | +```py |
| 55 | +import matplotlib.pyplot as plt |
| 56 | +import numpy as np |
| 57 | + |
| 58 | +x = np.linspace(0, 2 * np.pi, 100) |
| 59 | +y = np.sin(x) |
| 60 | + |
| 61 | +plt.figure(figsize=(8, 4), facecolor='lightblue') |
| 62 | +ax = plt.subplot(1, 1, 1) |
| 63 | +ax.plot(x, y) |
| 64 | +ax.set_title('Simple Sine Wave') |
| 65 | +ax.set_xlabel('X-axis') |
| 66 | +ax.set_ylabel('Y-axis') |
| 67 | + |
| 68 | +plt.show() |
| 69 | +``` |
| 70 | + |
| 71 | +The output of this code is: |
| 72 | + |
| 73 | + |
0 commit comments