1 回答

TA貢獻1794條經驗 獲得超7個贊
試試這個方法:
使用日期定位器將 x 軸格式化為您需要的日期范圍。日期定位器可用于定義以秒、分鐘……為單位的時間間隔:
SecondLocator:定位秒
MinuteLocator:定位分鐘
HourLocator:定位時間
DayLocator:定位一個月中的指定日期
MonthLocator:定位月份
YearLocator:定位年份
在示例中,我使用MinuteLocator
, 間隔 15 分鐘。
在繪圖中導入matplotlib.dates
工作日期:
import?matplotlib.dates?as?mdates
import?pandas?as?pd import?matplotlib.pyplot?as?plt
獲取您的數據
# Sample data
# Data
df = pd.DataFrame({
? ? 'Date': ['07/14/2020', '07/14/2020', '07/14/2020', '07/14/2020'],
? ? 'Time': ['12:15:00 AM', '12:30:00 AM', '12:45:00 AM', '01:00:00 AM'],
? ? 'Temperature': [22.5, 22.5, 22.5, 23.0]
})
從字符串轉換Time period為日期對象:
# Convert data to Date and Time
df["Time period"] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
定義min和max間隔:
min = min(df['Time period'])
max = max(df['Time period'])
創建你的情節:
# Plot
# Create figure and plot space
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot()
使用定位器設置時間間隔:
# Set Time Interval
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=15))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
設置繪圖選項并繪制:
# Set labels
ax.set(xlabel="Time",
? ? ? ?ylabel="Temperature",
? ? ? ?title="Temperature distribution Graph", xlim=[min , max])
# Plot chart
ax.plot('Time period', 'Temperature', data=df, linewidth=2, color='g')
ax.grid(True)
fig.autofmt_xdate()
plt.show()
添加回答
舉報