Pandas Plots: Separate color for weekends, pretty printing times on x axis

后端 未结 2 1369
青春惊慌失措
青春惊慌失措 2020-12-28 22:53

I created a plot which looks like\"enter

I have a few issues:

  1. How can i
2条回答
  •  粉色の甜心
    2020-12-28 23:11

    Now that Pandas supports the powerful .dt namespace on every series, it is possible to identify the start and end of each weekend without any explicit Python loops. Simply filter your time values with t.dt.dayofweek >= 5 to select only times falling on the weekend, and then group by a made-up value that is different every week — here I use year * 100 + weekofyear because the result looks like 201603 which is fairly pleasant to read for debugging.

    The resulting function is:

    def highlight_weekends(ax, timeseries):
        d = timeseries.dt
        ranges = timeseries[d.dayofweek >= 5].groupby(d.year * 100 + d.weekofyear).agg(['min', 'max'])
        for i, tmin, tmax in ranges.itertuples():
            ax.axvspan(tmin, tmax, facecolor='orange', edgecolor='none', alpha=0.1)
    

    Simply pass it the axis and the time series that is your x axis, and it will highlight the weekends for you!

提交回复
热议问题