如何在 matplotlib 图中突出显示周末?

how to highlight weekends in matplotlib plots?(如何在 matplotlib 图中突出显示周末?)
本文介绍了如何在 matplotlib 图中突出显示周末?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

对于一个简单的时间序列:

将 pandas 导入为 pddf = 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')#显示(df)df['foo'].plot()x =plt.xticks(ticks=df.reset_index().dt.values,标签=df.dt_label,旋转=90,水平对齐='right')

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

编辑

For a simple time series:

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')

How can I highlight the x-axis labels for weekends?

edit

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

suggests:

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)

but applying it with

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

will not change the plot

解决方案

I've extended your sample data a little so we can can make sure that we can highlight more than a single weekend instance.

In this solution I create a column 'weekend', which is a column of bools indicating whether the corresponding date was at a weekend.

We then loop over these values and make a call to 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)

这篇关于如何在 matplotlib 图中突出显示周末?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)