python - 在 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 日是一个星期四。
解决方案
当我们不知道示例中的内容时,我们无法回答为什么它显示错误的工作日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()
推荐阅读
- java - JavaFX 控制器未链接到 JavaFX fxml 文件
- sql-server - 如何从 AWS 托管的数据库中提取数据到本地或 Azure SQL 数据库
- amazon-web-services - 雅典娜 - CTAS 文件名
- docker - 离线时将谷歌云注册表与 docker 一起使用
- java - 错误:java:找不到符号符号:类 MockitoJUnitRunner
- ios - 如何在颤动中为 CupertinoDatePicker 小部件设置最短时间?
- javascript - phpmailer和javascript配置
- c - 如何从应用程序中执行调试器命令
- mysql - 相关视频 数据库表结构
- c# - 将数据和文件从 MVC 控制器 (NET Framework 4.6.1) 发送到 WebAPI 控制器 (NET Core 3.0)