python - 基于python中条件的多色时间序列线图使用线集合
问题描述
示例图 我有一个数据框,其中包含雪水和温度数据的时间序列。我正在寻找一个雪水的时间序列图,它在雪水线图中显示两种颜色,如果温度 < = 273 deg K,则为“蓝色”,如果温度 > 273 deg K,则为“红色”。我尝试遵循 matplotib 文档(https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html)但没有成功。将不胜感激一些见解。谢谢!
我的数据框如下: Date (datetime64[ns]); 雪水 (float64) 和温度 (float64)
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 轴上有日期时间
解决方案
尽管可能有更好的方法,但这确实起到了作用:
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()
推荐阅读
- ios - 无法将 ComparisonResult 转换为闭包结果类型 Bool
- security - Cloud Foundry 后端和公共应用程序
- cmake - Homebrew 自动开始下载,写入失败
- oracle - Oracle 中 DBMS_JOB 的旧行为
- android - 来自具有相同 id 的两个布局的两个组件
- php - 对数组的交集进行分组
- java - 如果是 servlet mkdirs() 总是返回 false ..并且无法创建目录
- java - Spring boot - NotEmpty 注释仅适用于特定控制器
- perl - Perl 日志文件模式匹配循环内循环
- python - Pandas - 如何将数据帧转换为新数据类型但忽略标题/第一行