Matplotlib 3.7.0(2023年2月13日)中的新功能#

有关自上次修订以来的所有问题和拉取请求列表,请参阅 3.10.3 (2025年5月8日) 的 GitHub 统计数据

绘图和批注改进#

pie图的hatch参数#

pie现在接受一个*hatch*关键字,该关键字接受一个孵化图案或孵化图案列表作为输入

fig, (ax1, ax2) = plt.subplots(ncols=2)
x = [10, 30, 60]

ax1.pie(x, hatch=['.', 'o', 'O'])
ax2.pie(x, hatch='.O')

ax1.set_title("hatch=['.', 'o', 'O']")
ax2.set_title("hatch='.O'")

(源代码, 2x.png, png)

Two pie charts, identified as ax1 and ax2, both have a small blue slice, a medium orange slice, and a large green slice. ax1 has a dot hatching on the small slice, a small open circle hatching on the medium slice, and a large open circle hatching on the large slice. ax2 has the same large open circle with a dot hatch on every slice.

极坐标图中绘制的极坐标误差#

在极坐标图上绘制误差条时,现在根据极坐标绘制误差帽和误差线。

../../_images/sphx_glr_polar_error_caps_001.png

`bar_label`中新增的格式字符串选项#

bar_labelfmt参数现在接受{}样式的格式字符串

import matplotlib.pyplot as plt

fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio']
fruit_counts = [4000, 2000, 7000]

fig, ax = plt.subplots()
bar_container = ax.bar(fruit_names, fruit_counts)
ax.set(ylabel='pints sold', title='Gelato sales by flavor', ylim=(0, 8000))
ax.bar_label(bar_container, fmt='{:,.0f}')

(源代码, 2x.png, png)

它还接受可调用对象

animal_names = ['Lion', 'Gazelle', 'Cheetah']
mph_speed = [50, 60, 75]

fig, ax = plt.subplots()
bar_container = ax.bar(animal_names, mph_speed)
ax.set(ylabel='speed in MPH', title='Running speeds', ylim=(0, 80))
ax.bar_label(
    bar_container, fmt=lambda x: '{:.1f} km/h'.format(x * 1.61)
)

(源代码, 2x.png, png)

批注的ellipse boxstyle选项#

boxstyle的'ellipse'选项现在可以用于创建带有椭圆形轮廓的批注。它可以作为长文本的闭合曲线形状,而不是可能变得很大的'circle' boxstyle。

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 5))
t = ax.text(0.5, 0.5, "elliptical box",
        ha="center", size=15,
        bbox=dict(boxstyle="ellipse,pad=0.3"))

(源代码, 2x.png, png)

imshowextent现在可以用单位表示#

imshowset_extent的*extent*参数现在可以用单位表示。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(layout='constrained')
date_first = np.datetime64('2020-01-01', 'D')
date_last = np.datetime64('2020-01-11', 'D')

arr = [[i+j for i in range(10)] for j in range(10)]

ax.imshow(arr, origin='lower', extent=[0, 10, date_first, date_last])

plt.show()

(源代码, 2x.png, png)

图例条目顺序反转#

通过向legend传递reverse=True,现在可以反转图例条目的顺序。

pcolormesh支持RGB(A)颜色#

pcolormesh方法现在可以处理用RGB(A)值指定的显式颜色。要指定颜色,数组必须是3D的,形状为(M, N, [3, 4])

import matplotlib.pyplot as plt
import numpy as np

colors = np.linspace(0, 1, 90).reshape((5, 6, 3))
plt.pcolormesh(colors)
plt.show()

(源代码, 2x.png, png)

查看刻度、刻度标签和网格线的当前显示设置#

新的get_tick_params方法可用于检索将应用于图中任何额外刻度、刻度标签和网格线的显示设置

>>> import matplotlib.pyplot as plt

>>> fig, ax = plt.subplots()
>>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red',
...                          direction='out', which='major')
>>> ax.yaxis.get_tick_params(which='major')
{'direction': 'out',
'left': True,
'right': False,
'labelleft': True,
'labelright': False,
'gridOn': False,
'labelsize': 30,
'labelcolor': 'red'}
>>> ax.yaxis.get_tick_params(which='minor')
{'left': True,
'right': False,
'labelleft': True,
'labelright': False,
'gridOn': False}

样式文件可以从第三方包导入#

第三方包现在可以按如下方式分发全局可用的样式文件。假设一个包可以像import mypackage一样导入,并且带有一个mypackage/__init__.py模块。那么mypackage/presentation.mplstyle样式表可以作为plt.style.use("mypackage.presentation")使用。

该实现实际上不导入mypackage,这使得此过程可以安全地防止可能的导入时副作用。也支持子包(例如dotted.package.name)。

3D绘图改进#

3D图平移和缩放按钮#

3D图工具栏中的平移和缩放按钮现在已启用。取消选择两者以旋转图形。当缩放按钮按下时,使用鼠标左键绘制一个边界框可放大,使用鼠标右键绘制边界框可缩小。缩放3D图时,当前视图的宽高比保持固定。

在3D中设置等长宽比的adjustable关键字参数#

在为3D图设置等长宽比时,用户可以选择修改数据限制或边界框,使其与2D坐标轴保持一致。

import matplotlib.pyplot as plt
import numpy as np
from itertools import combinations, product

aspects = ('auto', 'equal', 'equalxy', 'equalyz', 'equalxz')
fig, axs = plt.subplots(1, len(aspects), subplot_kw={'projection': '3d'},
                        figsize=(12, 6))

# Draw rectangular cuboid with side lengths [4, 3, 5]
r = [0, 1]
scale = np.array([4, 3, 5])
pts = combinations(np.array(list(product(r, r, r))), 2)
for start, end in pts:
    if np.sum(np.abs(start - end)) == r[1] - r[0]:
        for ax in axs:
            ax.plot3D(*zip(start*scale, end*scale), color='C0')

# Set the aspect ratios
for i, ax in enumerate(axs):
    ax.set_aspect(aspects[i], adjustable='datalim')
    # Alternatively: ax.set_aspect(aspects[i], adjustable='box')
    # which will change the box aspect ratio instead of axis data limits.
    ax.set_title(f"set_aspect('{aspects[i]}')")

plt.show()

(源代码, 2x.png, png)

Poly3DCollection支持着色#

现在可以对Poly3DCollection进行着色。这在从3D模型获取多边形时非常有用。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

# Define 3D shape
block = np.array([
    [[1, 1, 0],
     [1, 0, 0],
     [0, 1, 0]],
    [[1, 1, 0],
     [1, 1, 1],
     [1, 0, 0]],
    [[1, 1, 0],
     [1, 1, 1],
     [0, 1, 0]],
    [[1, 0, 0],
     [1, 1, 1],
     [0, 1, 0]]
])

ax = plt.subplot(projection='3d')
pc = Poly3DCollection(block, facecolors='b', shade=True)
ax.add_collection(pc)
plt.show()

(源代码, 2x.png, png)

3D平面颜色的rcParam#

rcParams rcParams["axes3d.xaxis.panecolor"](默认值:(0.95, 0.95, 0.95, 0.5))、rcParams["axes3d.yaxis.panecolor"](默认值:(0.9, 0.9, 0.9, 0.5))、rcParams["axes3d.zaxis.panecolor"](默认值:(0.925, 0.925, 0.925, 0.5))可用于更改3D图中背景面板的颜色。请注意,通常最好给它们设置略微不同的阴影以获得“3D效果”,并使它们稍微透明(alpha < 1)。

import matplotlib.pyplot as plt
with plt.rc_context({'axes3d.xaxis.panecolor': (0.9, 0.0, 0.0, 0.5),
                     'axes3d.yaxis.panecolor': (0.7, 0.0, 0.0, 0.5),
                     'axes3d.zaxis.panecolor': (0.8, 0.0, 0.0, 0.5)}):
    fig = plt.figure()
    fig.add_subplot(projection='3d')

(源代码, 2x.png, png)

图和坐标轴布局#

colorbar现在有了一个location关键字参数#

colorbar方法现在支持*location*关键字参数,以便更轻松地定位颜色条。当使用*cax*关键字参数提供自己的内嵌坐标轴时,这非常有用,并且行为类似于未提供坐标轴的情况(*location*关键字会透传)。*orientation*和*ticklocation*不再是必需的,因为它们由*location*确定。如果不需要自动设置,仍然可以提供*ticklocation*。(*orientation*也可以提供,但必须与*location*兼容。)

例如:

import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(19680801)
imdata = rng.random((10, 10))
fig, ax = plt.subplots(layout='constrained')
im = ax.imshow(imdata)
fig.colorbar(im, cax=ax.inset_axes([0, 1.05, 1, 0.05]),
             location='top')

(源代码, 2x.png, png)

使用constrained_layout可以将图例放置在图外#

如果图例由以字符串“outside”开头的*loc*关键字参数指定,则受限布局将为其腾出空间。这些代码与坐标轴代码不同,例如“outside upper right”会在图的顶部为图例腾出空间,而“outside right upper”会在图的右侧为图例腾出空间。详情请参阅图例指南

subplot_mosaic中每个子图的关键字参数#

现在可以在Figure.subplot_mosaicpyplot.subplot_mosaic中,通过add_subplot的每次特定调用,将关键字参数传递给坐标轴创建。

fig, axd = plt.subplot_mosaic(
    "AB;CD",
    per_subplot_kw={
        "A": {"projection": "polar"},
        ("C", "D"): {"xscale": "log"},
        "B": {"projection": "3d"},
    },
)

(源代码, 2x.png, png)

这对于创建具有混合投影的马赛克图特别有用,但任何关键字参数都可以透传。

subplot_mosaic不再是临时性的#

Figure.subplot_mosaicpyplot.subplot_mosaic的API现在被认为是稳定的,并将在Matplotlib正常的弃用流程下进行更改。

小部件改进#

按钮小部件的自定义样式#

按钮小部件的额外自定义样式可以通过RadioButtons的*label_props*和*radio_props*参数实现;以及CheckButtons的*label_props*、*frame_props*和*check_props*参数实现。

from matplotlib.widgets import CheckButtons, RadioButtons

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(5, 2), width_ratios=[1, 2])
default_rb = RadioButtons(ax[0, 0], ['Apples', 'Oranges'])
styled_rb = RadioButtons(ax[0, 1], ['Apples', 'Oranges'],
                         label_props={'color': ['red', 'orange'],
                                      'fontsize': [16, 20]},
                         radio_props={'edgecolor': ['red', 'orange'],
                                      'facecolor': ['mistyrose', 'peachpuff']})

default_cb = CheckButtons(ax[1, 0], ['Apples', 'Oranges'],
                          actives=[True, True])
styled_cb = CheckButtons(ax[1, 1], ['Apples', 'Oranges'],
                         actives=[True, True],
                         label_props={'color': ['red', 'orange'],
                                      'fontsize': [16, 20]},
                         frame_props={'edgecolor': ['red', 'orange'],
                                      'facecolor': ['mistyrose', 'peachpuff']},
                         check_props={'color': ['darkred', 'darkorange']})

ax[0, 0].set_title('Default')
ax[0, 1].set_title('Stylized')

(源代码, 2x.png, png)

按钮小部件中的blit渲染#

ButtonCheckButtonsRadioButtons小部件现在支持blit渲染以实现更快的渲染(在支持的后端上),通过向构造函数传递useblit=True即可。在支持的后端上,blit渲染默认启用。

其他改进#

图钩子#

新的rcParams["figure.hooks"](默认值:[])提供了一种机制,用于在pyplot图形上注册任意自定义;它是一个“dotted.module.name:dotted.callable.name”字符串列表,指定了由pyplot.figure创建的每个图形上调用的函数;这些函数可以例如附加回调或修改工具栏。有关工具栏自定义的示例,请参阅mplcvd -- an example of figure hook

新增及改进的叙述性文档#

  • 全新的动画教程。

  • 新增分组和堆叠的条形图示例。

  • 贡献指南中新增了面向新贡献者的章节并重新组织了git说明。

  • 重新组织了批注教程。