我有一個圖,其中我的 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 日是一個星期四。

uj5u.com熱心網友回復:
當我們不知道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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/311132.html
標籤:Python matplotlib
