Python視覺圖 x軸 日期處理

SharkYun
Jun 11, 2021

--

  • 在資料科學裡 我們會經常需要把數據圖形化來觀看數據

圖形視覺化中以時間軸為x-axis應該是比較常見的,不管在R語言中還是Python中,都可以直接plot(x , y)直接繪製出來,但有很大概率座標軸會出現文字重疊。因為將時間直接當做字串處理就會把每個日期都打印出來,若用時間為格式然後簡單的呈現,必須先將資料轉換為時間型別,再用matplotlib.dates設定。

範例圖為 以日期為x軸的時候 日期文字重疊的問題(x軸密密麻麻的情況)

import pandas as pd
import matplotlib.dates as mdates #處理日期
import matplotlib.pyplot as plt
newdate = pd.to_datetime(date)
fig = plt.figure(figsize = (18,5))
fig.gca().xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m-%d’)) #設定x軸主刻度顯示格式(日期)
fig.gca().xaxis.set_major_locator(mdates.DayLocator(interval=14)) #設定x軸主刻度間距
ax = fig.add_subplot()ax.plot(newdate,test, color=’red’, label=’Real’,
markerfacecolor=’red’,markersize=6)
ax.plot(newdate,predictions, color=’#121466', label=’Pred’,
markerfacecolor=’#121466',markersize=6)

P.S 上面程式碼中最重要的是部分是

newdate = pd.to_datetime(date)

圖裡你能看到date跟newdate的單位差別

type(date) #returns 'list'
type(newdate) #returns pandas.core.indexes.datetimes.DatetimeIndex

得把x軸原單位轉換成時間的格式 才能做matplotlib.dates得刻度設定~

時間刻度相同的道理

你可以把DateFormatter就要改成%Y-%m跟DayLocator改成MonthLocator, x軸的單位就變成月,最後在設定interval. 以下範例為一個月一個單位

fig.gca().xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m’)) #設定x軸主刻度顯示格式(日期)
fig.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=1)) #設定x軸主刻度間距

覺得有用的話 記得點讚 & follow 喔~

Reference:

https://blog.csdn.net/ly_ysys629/article/details/73822716

https://ithelp.ithome.com.tw/articles/10127225

--

--

SharkYun
SharkYun

No responses yet