【问题标题】:multicolored time series line plot based on condition in python using line collection基于python中条件的多色时间序列线图使用线集合
【发布时间】:2023-03-22 01:28:01
【问题描述】:

Example Plot 我有一个数据框,其中包含雪水和温度数据的时间序列。我正在寻找一个雪水的时间序列图,它在雪水线图中显示两种颜色,如果温度 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 轴上带有日期时间

【问题讨论】:

  • 请贴出您编写的相关代码并解释为什么它不起作用。

标签: python pandas matplotlib


【解决方案1】:

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

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

【讨论】:

    【解决方案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()
    

    【讨论】:

    • 谢谢,我从你的帖子中得到了一些想法,虽然它并没有完全回答我的问题......
    • 有什么区别?数据已在回答后更正,并添加了预期的图表。
    • 数据没有更正,我只是将温度单位从摄氏度改为摄氏度,问题还是一样的......不同的是我需要在 x 轴上的时间并且y轴取决于另一个变量...在经历了包括您在内的许多其他代码之后,我设法得到了一些东西...我添加了我得到的图表,以便其他有类似问题的人可以受益...我真诚地感谢您贡献!
    • 感谢您的解释。我也很高兴能帮你解决问题。请接受我的回答。
    猜你喜欢
    • 2018-07-01
    • 2018-04-02
    • 1970-01-01
    • 2018-12-13
    • 2015-05-28
    • 2018-09-11
    • 2020-04-26
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多