【问题标题】:Matplotlib plot winter periods with background polygons [duplicate]Matplotlib用背景多边形绘制冬季[重复]
【发布时间】:2021-11-01 04:00:00
【问题描述】:

我想在彩色背景上绘制一个时间序列,显示冬季是什么时候。

dates = pd.date_range("2000-01-01", "2004-01-01", freq="D")
df = pd.DataFrame({"y": np.random.random(len(dates))}, index=dates)

f, ax = plt.subplots(figsize=(12, 4))
ax.plot(df.index, df["y"])

我想通过突出冬季(“DJF”)来引导视线

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    结合使用this SO answeroverplotting background polygons SO answer here 定义的连续函数,我们可以实现既定目标。

    我们使用ax.axvspan 函数来绘制 X1: X2 之间的跨度

    f, ax = plt.subplots(figsize=(12, 4))
    ax.plot(df.index, df["y"])
    
    # plot winter spans in background
    # calculate days that are in the winter season (DJF)
    # 0 = DJF, 1 = MAM, 2 = JJA, 3 = SON
    is_winter = (df.reset_index()["index"].dt.month % 12 // 3) == 0
    winter_time_indexes = np.argwhere(is_winter.values).flatten()
    
    def consecutive(data, stepsize=1):
        # https://stackoverflow.com/a/7353335/9940782
        return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)
    
    # calculate each consecutive index as a winter period
    winters = consecutive(winter_time_indexes)
    for winter in winters:
        time_min, time_max = df.index.values[winter.min()], df.index.values[winter.max()]
        ax.axvspan(time_min, time_max, facecolor='C3', alpha=0.5)
    

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 2016-06-12
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      相关资源
      最近更新 更多