python - 如何突出情节中的周末?

标签 python matplotlib time-series weekend

对于简单的时间序列:

import pandas as pd
df = pd.DataFrame({'dt':['2020-01-01', '2020-01-02', '2020-01-04', '2020-01-05', '2020-01-06'], 'foo':[1,2, 4,5,6]})
df['dt'] = pd.to_datetime(df.dt)
df['dt_label']= df['dt'].dt.strftime('%Y-%m-%d %a')
df = df.set_index('dt')
#display(df)
df['foo'].plot()
x =plt.xticks(ticks=df.reset_index().dt.values, labels=df.dt_label, rotation=90, horizontalalignment='right')

如何突出显示周末的 x 轴标签?

编辑

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

建议:

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)

但应用它

highlight_weekends(ax, df.reset_index().dt)

不会改变剧情

最佳答案

我对您的示例数据进行了一些扩展,以便我们可以确保我们可以突出显示多个周末实例。

在此解决方案中,我创建了一个列 'weekend' ,这是一列 bool 值,指示相应的日期是否是周末。

然后我们循环这些值并调用 ax.axvspan

import pandas as pd
import matplotlib.pyplot as plt

# Add a couple of extra dates to sample data
df = pd.DataFrame({'dt': ['2020-01-01',
                          '2020-01-02',
                          '2020-01-04',
                          '2020-01-05',
                          '2020-01-06',
                          '2020-01-07',
                          '2020-01-09',
                          '2020-01-10',
                          '2020-01-11',
                          '2020-01-12']})
# Fill in corresponding observations
df['foo'] = range(df.shape[0])

df['dt'] = pd.to_datetime(df.dt)

df['dt_label']= df['dt'].dt.strftime('%Y-%m-%d %a')

df = df.set_index('dt')

ax = df['foo'].plot()
plt.xticks(ticks=df.reset_index().dt.values, 
           labels=df.dt_label,
           rotation=90,
           horizontalalignment='right')

# Create an extra column which highlights whether or not a date occurs at the weekend
df['weekend'] = df['dt_label'].apply(lambda x: x.endswith(('Sat', 'Sun')))

# Loop over weekend pairs (Saturdays and Sundays), and highlight
for i in range(df['weekend'].sum() // 2):
    ax.axvspan(df[df['weekend']].index[2*i],
               df[df['weekend']].index[2*i+1],
               alpha=0.5)

enter image description here

关于python - 如何突出情节中的周末?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287041/

相关文章:

python - 使用 Matplotlib 绘制散点图矩阵的刻度属性

python - 将默认颜色旋转 matplotlib 更改为特定颜色图

python - 网格搜索以在 python statsmodels 中自动选择 SARIMAX 订单模型

apache-spark - Spark 上的时间序列预测

python - 更新行的替代方法

python - GAE 上的 B2B 应用程序身份验证 - Google 帐户或自定义用户群(Django 或 Web2Py)?

python - 处理字符串中的转义字符

python - 在 basemap 中使用 pcolormesh 填充区域

Python:如何根据给定文件夹的内容创建名称列表?

python - 以编程方式求解函数方程