python - 带 datetime64[ns] 轴的 Matplotlib 多彩线

标签 python numpy matplotlib

这是我想要完成的任务的简化版本。我正在关注this example来自 matplotlib 网站的五彩线条。

我正在尝试绘制一组时间序列数据,并根据不同的数组对线条进行着色。在下面的简单示例中,我绘制了 y=x^2,并根据其导数 dy/dx = 2x 对线条进行了着色。

当我使用仅包含 float 的 x 轴时(如下所示),它工作得很好。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# Generate data
x = np.linspace(0,10, 60)
y = x ** 2
dydx = 2*x

# Create arrays needed for multicolored lines
points = np.array([x, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
norm = plt.Normalize(dydx.min(), dydx.max())

# Plot
fig, ax = plt.subplots(1,1, figsize=(10,10))

lc = LineCollection(segments, cmap='jet', norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line, ax=ax)

ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min(), y.max())
plt.show()

哪个产生

working graph of y=x^2 with shaded derivative

但是,如果我尝试绘制时间序列数据(其中 x 轴是 datetime64[ns] 数组),则无法正常工作。在下面的示例中,我将 x 替换为 x_time。

# Generate time array
ts = np.datetime64('2020-01-01T00:00:00')
te = np.datetime64('2020-01-01T01:00:00')
x_time = np.arange(ts, te, np.timedelta64(1,'m'), dtype='datetime64[ns]')

# Create arrays needed for multicolored lines
points = np.array([x_time, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
norm = plt.Normalize(dydx.min(), dydx.max())

# Plot
fig, ax = plt.subplots(1,1, figsize=(10,10))

lc = LineCollection(segments, cmap='jet', norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line, ax=ax)

ax.set_xlim(x_time.min(), x_time.max())
ax.set_ylim(y.min(), y.max())
plt.show()

这会产生一个带有右侧 x 任何 y 轴刻度的图形,但没有线条

enter image description here

编辑: 好吧,我知道线路去了哪里。当我创建 segments 数组时,它将 datetime64[ns] 转换为整数表示形式。通常,matplotlib 能够将其解释为日期时间,但在本例中,由于 LineCollection,它将其保留为 int

设置ax.set_xlim(segments[:,:,0].min(),segments[:,:,0].max())显示我的线,但轴是错误的(不显示为时间)。 enter image description here

最佳答案

您需要

  1. 将日期转换为代表 matplotlib 日期时间格式的数字
  2. 告诉轴它应该勾选日期时间。

所以:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import matplotlib.dates as mdates
# Generate data
x = np.linspace(0,10, 60)
y = x ** 2
dydx = 2*x

# Generate time array
ts = np.datetime64('2020-01-01T00:00:00')
te = np.datetime64('2020-01-01T01:00:00')
x_time = np.arange(ts, te, np.timedelta64(1,'m'), dtype='datetime64[ns]')
x_time = mdates.date2num(x_time)
# Create arrays needed for multicolored lines
points = np.array([x_time, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
norm = plt.Normalize(dydx.min(), dydx.max())

# Plot
fig, ax = plt.subplots(1,1, figsize=(10,10))

lc = LineCollection(segments, cmap='jet', norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line, ax=ax)

ax.xaxis_date()
ax.autoscale()

plt.show()

关于python - 带 datetime64[ns] 轴的 Matplotlib 多彩线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59689024/

相关文章:

python - 让 C 库使用 ctypes 调用 python 函数

python - numpy.empty 给出非空数组

python-3.x - MatPlotLib + GeoPandas : Plot Multiple Layers, 控制图大小

python - 使用matplotlib生成平滑线图

python - 在 matplotlib 中合并两个已经存在的图(png 文件)

python - 如何在 pip 中安装具有公共(public)依赖项的私有(private)模块?

python - python中的多进程会重新初始化全局变量吗?

python - 将 CSV 转换为 numpy

python - Python/numpy/pandas 中函数 f(x,y) 结果的矩阵

python - 具有意外结果的正弦波的傅里叶变换