绘制日期和字符串#

使用Matplotlib绘图方法最基本的方式是传入数值型的numpy数组作为坐标。例如,如果 xy 是浮点数(或整数)的numpy数组,plot(x, y) 将会正常工作。如果 numpy.asarray 可以将 xy 转换为浮点数数组,绘图方法也将奏效;例如,x 可以是Python列表。

如果数据类型存在“单位转换器”,Matplotlib 也能够转换其他数据类型。Matplotlib 内置了两个转换器,一个用于日期,另一个用于字符串列表。其他下游库有自己的转换器来处理它们的数据类型。

向 Matplotlib 添加转换器的方法在 matplotlib.units 中有描述。这里我们简要概述内置的日期和字符串转换器。

日期转换#

如果 x 和/或 ydatetime 列表或 numpy.datetime64 数组,Matplotlib 内置的转换器会将其转换为浮点数,并为坐标轴添加适用于日期的刻度定位器和格式化器。参见 matplotlib.dates

在以下示例中,x 轴获得了一个将 numpy.datetime64 转换为浮点数的转换器,一个在月份开始处放置刻度的定位器,以及一个适当标记刻度的格式化器。

import numpy as np

import matplotlib.dates as mdates
import matplotlib.units as munits

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')
time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')
x = np.arange(len(time))
ax.plot(time, x)
axes units

请注意,如果我们尝试在 x 轴上绘制一个浮点数,它将以转换器“纪元”(在此情况下为 1970-01-01)以来的天数为单位进行绘制(参见 Matplotlib 日期格式)。因此,当我们绘制值 0 时,刻度从 1970-01-01 开始。(定位器现在也选择每两年一个刻度,而不是每个月)

fig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')
time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')
x = np.arange(len(time))
ax.plot(time, x)
# 0 gets labeled as 1970-01-01
ax.plot(0, 0, 'd')
ax.text(0, 0, ' Float x=0', rotation=45)
axes units

我们可以自定义定位器和格式化器;有关完整列表,请参阅日期刻度定位器日期格式化器,以及日期刻度定位器和格式化器以获取使用示例。这里我们每隔一个月定位一次,并仅使用月份的 3 个字母名称(使用 "%b")进行格式化(参见 strftime 了解格式代码)。

fig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')
time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')
x = np.arange(len(time))
ax.plot(time, x)
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=np.arange(1, 13, 2)))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ax.set_xlabel('1980')
axes units

默认的定位器是 AutoDateLocator,默认的格式化器是 AutoDateFormatter。还有“简洁”的格式化器和定位器,它们提供更紧凑的标签,可以通过 rcParams 进行设置。请注意,在年初,“Jan”这个冗余标签被“1980”取代。更多示例请参见 使用 ConciseDateFormatter 格式化日期刻度

plt.rcParams['date.converter'] = 'concise'

fig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')
time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')
x = np.arange(len(time))
ax.plot(time, x)
axes units

我们可以通过传入适当的日期作为限制,或者传入以纪元以来的天数为单位的浮点值来设置轴的限制。如果需要,我们可以从 date2num 获取此值。

fig, axs = plt.subplots(2, 1, figsize=(5.4, 3), layout='constrained')
for ax in axs.flat:
    time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')
    x = np.arange(len(time))
    ax.plot(time, x)

# set xlim using datetime64:
axs[0].set_xlim(np.datetime64('1980-02-01'), np.datetime64('1980-04-01'))

# set xlim using floats:
# Note can get from mdates.date2num(np.datetime64('1980-02-01'))
axs[1].set_xlim(3683, 3683+60)
axes units

字符串转换:分类绘图#

有时我们希望在轴上标注类别而不是数字。Matplotlib 允许使用“分类”转换器来实现这一点(参见 category)。

data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}
names = list(data.keys())
values = list(data.values())

fig, axs = plt.subplots(1, 3, figsize=(7, 3), sharey=True, layout='constrained')
axs[0].bar(names, values)
axs[1].scatter(names, values)
axs[2].plot(names, values)
fig.suptitle('Categorical Plotting')
Categorical Plotting

请注意,“类别”是按照它们首次指定的顺序绘制的,并且随后以不同顺序进行的绘制不会影响原始顺序。此外,新添加的项将添加到末尾(参见下面的“pear”)

fig, ax = plt.subplots(figsize=(5, 3), layout='constrained')
ax.bar(names, values)

# plot in a different order:
ax.scatter(['lemon', 'apple'], [7, 12])

# add a new category, "pear", and put the other categories in a different order:
ax.plot(['pear', 'orange', 'apple', 'lemon'], [13, 10, 7, 12], color='C1')
axes units

请注意,当像上面那样使用 plot 时,绘图的顺序会映射到数据的原始顺序,因此新线按照指定的顺序绘制。

类别转换器将类别映射到整数,从零开始。因此,也可以使用浮点数手动将数据添加到轴上。请注意,如果传入的浮点数没有与之关联的“类别”,则数据点仍然可以绘制,但不会创建刻度。在下面的示例中,我们在 4.0 和 2.5 处绘制数据,但由于这些不是类别,因此未在这些位置添加刻度。

fig, ax = plt.subplots(figsize=(5, 3), layout='constrained')
ax.bar(names, values)
# arguments for styling the labels below:
args = {'rotation': 70, 'color': 'C1',
        'bbox': {'color': 'white', 'alpha': .7, 'boxstyle': 'round'}}


# 0 gets labeled as "apple"
ax.plot(0, 2, 'd', color='C1')
ax.text(0, 3, 'Float x=0', **args)

# 2 gets labeled as "lemon"
ax.plot(2, 2, 'd', color='C1')
ax.text(2, 3, 'Float x=2', **args)

# 4 doesn't get a label
ax.plot(4, 2, 'd', color='C1')
ax.text(4, 3, 'Float x=4', **args)

# 2.5 doesn't get a label
ax.plot(2.5, 2, 'd', color='C1')
ax.text(2.5, 3, 'Float x=2.5', **args)
axes units

可以通过指定类别或指定浮点数来设置分类轴的限制

fig, axs = plt.subplots(2, 1, figsize=(5, 5), layout='constrained')
ax = axs[0]
ax.bar(names, values)
ax.set_xlim('orange', 'lemon')
ax.set_xlabel('limits set with categories')
ax = axs[1]
ax.bar(names, values)
ax.set_xlim(0.5, 2.5)
ax.set_xlabel('limits set with floats')
axes units

分类轴对于某些图表类型很有帮助,但如果数据被读取为字符串列表(即使它旨在成为浮点数或日期列表),则可能导致混淆。这种情况有时发生在读取逗号分隔值(CSV)文件时。分类定位器和格式化器将在每个字符串值处放置一个刻度并同时对其进行标记。

fig, ax = plt.subplots(figsize=(5.4, 2.5), layout='constrained')
x = [str(xx) for xx in np.arange(100)]  # list of strings
ax.plot(x, np.arange(100))
ax.set_xlabel('x is list of strings')
axes units

如果不需要这样做,只需在绘图前将数据转换为浮点数。

fig, ax = plt.subplots(figsize=(5.4, 2.5), layout='constrained')
x = np.asarray(x, dtype='float')  # array of float.
ax.plot(x, np.arange(100))
ax.set_xlabel('x is array of floats')
axes units

确定轴上的转换器、格式化器和定位器#

有时,能够调试 Matplotlib 用于转换传入数据的内容会很有帮助。我们可以通过查询轴上的 converter 属性来做到这一点。我们还可以使用 get_major_locatorget_major_formatter 来查询格式化器和定位器。

请注意,默认情况下,转换器为 None

fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), layout='constrained')
x = np.arange(100)
ax = axs[0]
ax.plot(x, x)
label = f'Converter: {ax.xaxis.get_converter()}\n '
label += f'Locator: {ax.xaxis.get_major_locator()}\n'
label += f'Formatter: {ax.xaxis.get_major_formatter()}\n'
ax.set_xlabel(label)

ax = axs[1]
time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')
x = np.arange(len(time))
ax.plot(time, x)
label = f'Converter: {ax.xaxis.get_converter()}\n '
label += f'Locator: {ax.xaxis.get_major_locator()}\n'
label += f'Formatter: {ax.xaxis.get_major_formatter()}\n'
ax.set_xlabel(label)

ax = axs[2]
data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}
names = list(data.keys())
values = list(data.values())
ax.plot(names, values)
label = f'Converter: {ax.xaxis.get_converter()}\n '
label += f'Locator: {ax.xaxis.get_major_locator()}\n'
label += f'Formatter: {ax.xaxis.get_major_formatter()}\n'
ax.set_xlabel(label)
axes units

关于“单位”支持的更多信息#

对日期和类别的支持是 Matplotlib 内置的“单位”支持的一部分。这在 matplotlib.units基本单位 示例中有所描述。

单位支持通过查询传递给绘图函数的数据类型,并分派给列表中第一个接受该数据类型的转换器来工作。因此,在下面,如果 x 包含 datetime 对象,转换器将是 _SwitchableDateConverter;如果它包含字符串,它将被发送到 StrCategoryConverter

for k, v in munits.registry.items():
    print(f"type: {k};\n    converter: {type(v)}")
type: <class 'decimal.Decimal'>;
    converter: <class 'matplotlib.units.DecimalConverter'>
type: <class 'numpy.datetime64'>;
    converter: <class 'matplotlib.dates._SwitchableDateConverter'>
type: <class 'datetime.date'>;
    converter: <class 'matplotlib.dates._SwitchableDateConverter'>
type: <class 'datetime.datetime'>;
    converter: <class 'matplotlib.dates._SwitchableDateConverter'>
type: <class 'str'>;
    converter: <class 'matplotlib.category.StrCategoryConverter'>
type: <class 'numpy.str_'>;
    converter: <class 'matplotlib.category.StrCategoryConverter'>
type: <class 'bytes'>;
    converter: <class 'matplotlib.category.StrCategoryConverter'>
type: <class 'numpy.bytes_'>;
    converter: <class 'matplotlib.category.StrCategoryConverter'>

有许多下游库提供了自己的带有定位器和格式化器的转换器。物理单位支持由 astropypintunyt 等提供。

诸如 pandasnc-time-axis(因此也包括 xarray)这样的高级库提供了它们自己的日期时间支持。这种支持有时可能与 Matplotlib 原生日期时间支持不兼容,因此在使用这些库时,在使用 Matplotlib 定位器和格式化器时应谨慎。

脚本总运行时间: (0 分 7.864 秒)

由 Sphinx-Gallery 生成的画廊