python - 如果 x 轴是 Pandas 的日期时间索引,如何绘制多色线

标签 python pandas matplotlib

我正在尝试使用 pandas 系列绘制多色线。我知道 matplotlib.collections.LineCollection 会大幅提升效率。 但是 LineCollection 要求线段必须是 float 的。我想使用 pandas 的数据时间索引作为 x 轴。

points = np.array((np.array[df_index.astype('float'), values]).T.reshape(-1,1,2))
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments)
fig = plt.figure()
plt.gca().add_collection(lc)
plt.show()

但是图片不能让我满意。 有什么解决办法吗?

最佳答案

要生成多色线条,您需要先将日期转换为数字,因为 matplotlib 在内部仅适用于数值。

对于转换,matplotlib 提供了matplotlib.dates.date2num。它理解日期时间对象,因此您首先需要使用 series.index.to_pydatetime() 将时间序列转换为日期时间,然后应用 date2num

s = pd.Series(y, index=dates)
inxval = mdates.date2num(s.index.to_pydatetime())

然后您可以像往常一样使用数字点,例如绘制为 Polygon 或 LineCollection[ 1 , 2 ].

完整示例:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
from matplotlib.collections import LineCollection

dates = pd.date_range("2017-01-01", "2017-06-20", freq="7D" )
y = np.cumsum(np.random.normal(size=len(dates)))

s = pd.Series(y, index=dates)

fig, ax = plt.subplots()

#convert dates to numbers first
inxval = mdates.date2num(s.index.to_pydatetime())
points = np.array([inxval, s.values]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)

lc = LineCollection(segments, cmap="plasma", linewidth=3)
# set color to date values
lc.set_array(inxval)
# note that you could also set the colors according to y values
# lc.set_array(s.values)
# add collection to axes
ax.add_collection(lc)


ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
monthFmt = mdates.DateFormatter("%b")
ax.xaxis.set_major_formatter(monthFmt)
ax.autoscale_view()
plt.show()

enter image description here


由于人们似乎很难抽象出这个概念,下面是一段与上面相同的代码,但没有使用 pandas 且具有独立的颜色数组:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np; np.random.seed(42)
from matplotlib.collections import LineCollection

dates = np.arange("2017-01-01", "2017-06-20", dtype="datetime64[D]" )
y = np.cumsum(np.random.normal(size=len(dates)))
c = np.cumsum(np.random.normal(size=len(dates)))


fig, ax = plt.subplots()

#convert dates to numbers first
inxval = mdates.date2num(dates)
points = np.array([inxval, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)

lc = LineCollection(segments, cmap="plasma", linewidth=3)
# set color to date values
lc.set_array(c)
ax.add_collection(lc)

ax.xaxis_date()
ax.autoscale_view()
plt.show()

关于python - 如果 x 轴是 Pandas 的日期时间索引,如何绘制多色线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642966/

相关文章:

python - 对 groupby 之后的计数值创建的频率计数进行减去和除法

Python分解超长IF语句

python - Django - 从 Sqlite3 迁移到 Postgresql

python - Pandas 数据框 : How to convert numeric columns into pairwise categorical data?

Python Pandas : Updating row based on value from another column

python - 如何有效地改变 matplotlib 中补丁圆圈动画的颜色?

python - 如何检查一个句子是否正确(Python中的简单语法检查)?

python - 按类别获取最大值索引

python - 如何获取两个折线图(使用单独的 y 轴)以共享相同的日期 x 轴?

python - Matplotlib 分散不同的图像 (MNIST) 而不是 TSNE 的绘图