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

要查看自上次修订以来的所有问题和拉取请求列表,请参阅 GitHub 统计数据为 3.9.2 版本(2024年8月12日)

绘图和注释改进#

hatch 参数用于饼图#

pie 现在接受一个 hatch 关键字,该关键字接受一个 hatch 或 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'")

(Source code, 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}')

(Source code, 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)
)

(Source code, 2x.png, png)

ellipse 注释的 boxstyle 选项#

'ellipse' 选项现在可以用于 boxstyle 来创建带有椭圆形轮廓的注释。它可以作为较长的文本的闭合曲线形状使用,而不是 '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"))

(Source code, 2x.png, png)

imshow范围 现在可以用单位表示#

imshowset_extentextent 参数现在可以用单位表示。

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()

(Source code, 2x.png, png)

图例条目顺序反转#

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

pcolormesh 接受 RGB(A) 颜色#

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

import matplotlib.pyplot as plt
import numpy as np

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

(Source code, 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中设置等比例#

在为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()

(Source code, 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()

(Source code, 2x.png, png)

3D 面板颜色的 rcParam#

rcParams rcParams["axes3d.xaxis.panecolor"] (default: (0.95, 0.95, 0.95, 0.5)), rcParams["axes3d.yaxis.panecolor"] (default: (0.9, 0.9, 0.9, 0.5)), rcParams["axes3d.zaxis.panecolor"] (default: (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')

(Source code, 2x.png, png)

图形和轴布局#

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

colorbar 方法现在支持一个 location 关键字参数,以便更容易地定位颜色条。当使用 cax 关键字参数提供自己的插入轴时,这非常有用,并且行为类似于未提供轴的情况(其中 location 关键字被传递)。orientationticklocation 不再需要,因为它们由 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')

(Source code, 2x.png, png)

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

如果通过以字符串“outside”开头的 loc 关键字参数指定了图例,约束布局将为图例留出空间。代码与轴代码不同,其中“outside upper right”将在图的顶部为图例留出空间,而“outside right upper”将在图的右侧留出空间。详情请参阅 图例指南

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

现在可以通过关键字参数在 Figure.subplot_mosaicpyplot.subplot_mosaic 中每次调用 add_subplot 时传递给 Axes 的创建。

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

(Source code, 2x.png, png)

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

subplot_mosaic 不再处于试验阶段#

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

小部件改进#

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

可以通过 RadioButtonslabel_propsradio_props 参数,以及 CheckButtonslabel_propsframe_propscheck_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')

(Source code, 2x.png, png)

按钮小部件中的位块传输#

Button, CheckButtons, 和 RadioButtons 小部件现在支持在支持的后端上通过传递 useblit=True 给构造函数来实现更快的渲染。在支持的后端上,blitting 默认启用。

其他改进#

图表钩子#

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

新版与改进的叙事文档#

  • 全新的 动画 教程。

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

  • 为新贡献者新增章节,并在 贡献指南 中重新组织了git指令。

  • 重构 注解 教程。