首页 > 解决方案 > 在 x 轴 matplot 上突出显示周末

问题描述

我有一个图,其中我的 x 轴是 pandas 数据框中的 datetime64 对象。有没有办法以某种方式识别每个日期的星期几

from matplotlib.dates import MonthLocator, DateFormatter
import matplotlib.dates as mdates

fig1, ax1 = plt.subplots(figsize=(20,8))
ax = plt.plot(time_bookings.ymd, time_bookings.bookings, color="r", marker="o")

plt.grid(axis='x')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.title("Mean daily bookings")
plt.ylabel("Number of Bookings")
plt.xticks(rotation=90)
plt.xlabel("Time (Days)")


ax2 = plt.twiny()
ax2.set_xticks( plot.get_xticks() )
ax2.set_xticklabels(df.weekend)

plt.show()

这是我尝试过的,但似乎顶部标签稍后与底部不同步。顶层显示星期一为 0,但似乎它们已关闭。2018 年 3 月 1 日是一个星期四。

在此处输入图像描述

标签: pythonmatplotlib

解决方案


当我们不知道示例中的内容时,我们无法回答为什么它显示错误的工作日df。但是如何在图表中将周末显示为阶梯曲线呢?

import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter
import matplotlib.dates as mdates
import pandas as pd
import numpy as np

time_bookings = pd.DataFrame({'ymd': pd.date_range('02/26/2018', '05/03/2018'), 'bookings': np.random.randint(100,200,67)})

fig1, ax1 = plt.subplots(figsize=(20,8))
ax = plt.plot(time_bookings.ymd, time_bookings.bookings, color="r", marker="o")

plt.grid(axis='x')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.title("Mean daily bookings")
plt.ylabel("Number of Bookings")
plt.xticks(rotation=90)
plt.xlabel("Time (Days)")

yl = plt.ylim()
plt.fill_between(time_bookings.ymd,
         (time_bookings.ymd.dt.dayofweek >= 5).astype(int) * yl[1],
         step='mid',
         alpha=.3)
plt.ylim(yl)

plt.show()

在此处输入图像描述


推荐阅读