基于线集合的python中基于条件的多色时间序列线图

2024-09-29 21:55:05 发布

您现在位置:Python中文网/ 问答频道 /正文

Example Plot 我有一个数据框架,包括雪水和温度数据的时间序列。我希望创建一个雪水时间序列图,在雪水线图中显示两种颜色,如果温度为<;=273摄氏度和“红色”,如果温度>;273 deg K.我试图遵循matplotib文档(https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html),但没有成功。希望您能提供一些见解。谢谢大家!

我的数据帧如下:Date(datetime64[ns]);雪水(浮子64)和温度(浮子64)

from matplotlib.collections import LineCollection

Date                  Snowwater  Temperature
2014-01-01 01:00:00   5           240
2014-01-01 02:00:00   10          270
2014-01-01 03:00:00   11          273
2014-01-01 04:00:00   15          279
2014-01-01 05:00:00   20          300
2014-01-01 06:00:00   25          310

我正在寻找类似上面链接的示例图中的输出,但是y轴上有雪水值(线颜色为蓝色或红色,取决于温度),x轴上有日期时间


Tags: 数据框架dateplotmatplotlib颜色example时间
2条回答

我手动创建了数据,但LineCollection是一个 这是一个包含多行的对象,第一个参数是行列表

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

xs = [0, 1, 2, 3, 4, 5]
ys = [-2, -1, 0, 1, 5, 10]
lines = [[(x1, y1), (x2, y2)] for x1, y1, x2, y2 in zip(xs, ys, xs[1:], ys[1:])]

colors = ['r', 'r', 'b', 'b', 'b']
lc = LineCollection(lines, colors=colors)

fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
plt.show()

enter image description here

这确实起到了作用,尽管可能有更好的方法:

colors=['blue' if x < 273 else 'red' for x in df['AIR_T[K]']]
x = mpd.date2num(df['Date'])
y = df['SWE_St'].values
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, colors=colors)

fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.xaxis.set_major_locator(mpd.MonthLocator())
ax.xaxis.set_major_locator(ticker.MultipleLocator(200))
ax.xaxis.set_major_formatter(mpd.DateFormatter('%Y-%m-%d:%H:%M:%S'))
plt.setp(ax.xaxis.get_majorticklabels(), rotation=70)
plt.show()

result plot

相关问题 更多 >

    热门问题