Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib Layout and Configuration Functions

Matplotlib Layout and Configuration Functions


Matplotlib Reference Documentation Matplotlib Reference Documentation

Layout functions control subplot spacing and arrangement, configuration functions manage Matplotlib global parameters.

Function overview

Layout functions

function Function
subplots_adjust() Manually Adjust Subplot Spacing
tight_layout() Automatic tight layout
margins() Set data margins (the whitespace at both ends of the axes)
subplot_tool() Launch the interactive subplot adjustment tool

Configuration functions

function Function
rc() Set rc parameters (supports batch setting)
rc_context() Context manager for temporarily setting rc parameters
rcdefaults() Restore all rc parameters to their default values

Colormap functions

function Function
clim() Set the data range of the colormap
get_cmap() Get a colormap by specified name
set_cmap() Set the default colormap
gci() Get the current color-mappable object
sci() Set the current color-mappable object
imread() Read an image from a file into an array
imsave() Save an array as an image file

Output and interaction functions

function Function
show() Show all open Figures
draw() Force a re-render of the current Figure
draw_if_interactive() Render the Figure in interactive mode
pause() Pause for a specified number of seconds (processing GUI events during this time)
ion() / ioff() Turn interactive mode on/off
isinteractive() Check whether interactive mode is active
install_repl_displayhook() Install the REPL display hook
uninstall_repl_displayhook() Uninstall the REPL display hook
switch_backend() Switch the Matplotlib backend

Layout function examples

subplots_adjust() / tight_layout() / margins()

matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None,
    top=None, wspace=None, hspace=None)
matplotlib.pyplot.tight_layout(*, pad=1.08, h_pad=None, w_pad=None,
    rect=None)
matplotlib.pyplot.margins(*margins, x=None, y=None, tight=True)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

10

,

100

)

fig

,

axes

=

plt.

subplots

(

2

,

2

,

figsize

=

(

10

,

8

)

)

subplots_adjust manual control

fig.

subplots_adjust

(

left

=

0.1

,

right

=

0.95

,

                     top

=

0.9

,

bottom

=

0.1

,

                     hspace

=

0.4

,

wspace

=

0.3

)

for

i

,

ax

in

enumerate

(

axes.

flatten

(

)

)

:

    ax.

plot

(

x

,

np.

sin

(

x + i

)

)

    ax.

set_title

(

f

'Plot {i+1}'

)

    ax.

set_xlabel

(

'A long x label'

)

    ax.

set_ylabel

(

'A long y label'

)

   

Set margins

    ax.

margins

(

x

=

0.1

,

y

=

0.15

)

fig.

suptitle

(

'subplots_adjust() + margins()'

,

fontsize

=

14

)

plt.

show

(

)

print

(

"runoob: layout example"

)


Configuration function examples

rc() / rc_context() / rcdefaults()

matplotlib.pyplot.rc(group, **kwargs)
matplotlib.pyplot.rc_context(rc=None, fname=None)
matplotlib.pyplot.rcdefaults()

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Method 1: Set rcParams globally

plt.

rcParams

[

'font.size'

]

=

12

plt.

rcParams

[

'axes.grid'

]

=

True

Method 2: Batch setting with rc()

plt.

rc

(

'lines'

,

linewidth

=

2

,

color

=

'steelblue'

)

plt.

rc

(

'axes'

,

titlesize

=

14

,

grid

=

True

)

x

=

np.

linspace

(

0

,

10

,

50

)

rc_context temporary setting (only valid within the with block)

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

1

,

2

,

figsize

=

(

10

,

4

)

,

                                layout

=

'constrained'

)

ax1 uses the global rc settings

ax1.

plot

(

x

,

np.

sin

(

x

)

)

ax1.

set_title

(

'Global rc settings'

)

ax2 uses a temporary style override

with

plt.

rc_context

(

{

'lines.color'

:

'coral'

,

                     

'lines.linestyle'

:

'--'

,

                     

'axes.facecolor'

:

'#f0f0f0'

}

)

:

    ax2.

plot

(

x

,

np.

cos

(

x

)

)

    ax2.

set_title

(

'rc_context() overrides'

)

plt.

show

(

)

Restore the default

plt.

rcdefaults

(

)

print

(

"runoob: rc settings restored to defaults"

)


Colormap function examples

clim() / get_cmap() / set_cmap()

matplotlib.pyplot.clim(vmin=None, vmax=None)
matplotlib.pyplot.get_cmap(name=None, lut=None)
matplotlib.pyplot.set_cmap(cmap)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

data

=

np.

random

.

rand

(

10

,

10

)

View the current default colormap

print

(

'Default cmap:'

,

plt.

rcParams

[

'image.cmap'

]

)

Get a specific colormap

cmap

=

plt.

get_cmap

(

'plasma'

)

print

(

'Got cmap:'

,

cmap.

name

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

5

,

4

)

,

layout

=

'constrained'

)

im

=

ax.

imshow

(

data

,

cmap

=

'hot'

,

vmin

=

0.2

,

vmax

=

0.8

)

clim() can also be used to modify the range

plt.

clim

(

0.1

,

0.9

)

fig.

colorbar

(

im

,

ax

=

ax

,

label

=

'Value'

)

ax.

set_title

(

'imshow with clim()'

)

plt.

show

(

)

Set the global default colormap

plt.

set_cmap

(

'Blues'

)

print

(

'New default cmap:'

,

plt.

rcParams

[

'image.cmap'

]

)

Default cmap: viridis
Got cmap: plasma
New default cmap: Blues

imread() / imsave()

matplotlib.pyplot.imread(fname, format=None)
matplotlib.pyplot.imsave(fname, arr, **kwargs)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create image data

img

=

np.

random

.

rand

(

50

,

50

)

Save as PNG (no Figure needed)

plt.

imsave

(

'runoob_temp_image.png'

,

img

,

           cmap

=

'viridis'

)

print

(

"runoob: image saved via imsave()"

)

Read it back

loaded

=

plt.

imread

(

'runoob_temp_image.png'

)

print

(

"Loaded shape:"

,

loaded.

shape

)

print

(

"runoob: image loaded via imread()"

)

Loaded shape: (50, 50, 4)

Output and interaction function examples

ion() / ioff() / pause() / draw()

matplotlib.pyplot.ion()    # 开启交互模式
matplotlib.pyplot.ioff()   # 关闭交互模式
matplotlib.pyplot.isinteractive()  # 检查状态
matplotlib.pyplot.pause(interval)  # 暂停并处理事件
matplotlib.pyplot.draw()           # 强制重绘

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Interactive mode example (run in an environment that supports interaction)

print

(

'Interactive mode:'

,

plt.

isinteractive

(

)

)

Manually control rendering in non-interactive mode

plt.

ioff

(

)

fig

,

ax

=

plt.

subplots

(

)

x

=

np.

linspace

(

0

,

10

,

100

)

for

i

in

range

(

3

)

:

    ax.

clear

(

)

    ax.

plot

(

x

,

np.

sin

(

x + i *

0.5

)

)

    ax.

set_title

(

f

'Frame {i+1}'

)

    plt.

draw

(

)

             

Manual rendering

    plt.

pause

(

0.5

)

         

Pause for 0.5 seconds

plt.

show

(

)

print

(

"runoob: animation complete"

)

switch_backend()

matplotlib.pyplot.switch_backend(newbackend)

switch_backend() can only be called after pyplot is first imported and before any Figure is created. Switching the backend after creating a Figure requires using the experimental matplotlib.use()。

Matplotlib Reference Documentation Matplotlib Reference Documentation