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

基于线集合的python中基于条件的多色时间序列线图,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个数据框架,包括雪水和温度数据的时间序列。我希望创建一个雪水时间序列图,该图在雪水线图中显示两种颜色,如果温度273°K,则显示“红色”。我尝试遵循matplotib文档()但未成功。希望您能提供一些见解。谢谢大家! 我的数据帧如下:Date(datetime64[ns]);雪水(浮子64)和温度(浮子64) 我正在寻找类似上面链接的示例图中的输出,但y轴上有雪水值(线颜色为蓝色或红色,取决于温度),x轴上有日期时间我手动创建了数据,但LineCollection是一个 这是一个包含多行的

我有一个数据框架,包括雪水和温度数据的时间序列。我希望创建一个雪水时间序列图,该图在雪水线图中显示两种颜色,如果温度<=273°K,则显示“蓝色”,如果温度>273°K,则显示“红色”。我尝试遵循matplotib文档()但未成功。希望您能提供一些见解。谢谢大家!

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


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

我手动创建了数据,但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()

虽然可能有更好的方法,但这确实奏效了:

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()
colors=[[x<273时为“蓝色”,df时为“红色”['AIR\u T[K]]]
x=mpd.date2num(df['Date'])
y=df['SWE_St']值
点=np.数组([x,y]).T.重塑(-1,1,2)
分段=np。连接([点[:-1],点[1:],轴=1)
lc=线条集合(线段、颜色=颜色)
图,ax=plt.子批次()
ax.添加_集合(lc)
ax.自动缩放()
ax.xaxis.set\u major\u定位器(mpd.MonthLocator())
ax.xaxis.set\u major\u定位器(股票代码多路传输器(200))
ax.xaxis.set\u major\u格式化程序(mpd.DateFormatter(“%Y-%m-%d:%H:%m:%S”))
plt.setp(ax.xaxis.get_majorticklabels(),旋转=70)
plt.show()

请发布您所编写的相关代码,并解释其不起作用的原因。谢谢,我从您的帖子中获得了一些想法,尽管它没有完全回答我的问题……有什么区别?答案和预期图表添加后,数据已被更正。数据未被更正,我只是将温度单位从摄氏度更改为摄氏度,问题仍然是一样的…不同的是,我需要在x轴和y轴上的时间,这取决于另一个变量…我在经历了许多其他代码(包括你的代码)后,设法得到了一些东西。。。我添加了我得到的图表,以便其他有类似问题的人可以受益…我真诚地感谢您的贡献!谢谢你的解释。我也很高兴能帮你解决这个问题。请接受我的回答。
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()