python如何畫(huà)時(shí)間軸 DATE: 2026-05-05 07:03:31
在Python中,何畫(huà)我們可以使用matp??lotlib庫來(lái)繪制時(shí)間軸,時(shí)間以下是何畫(huà)詳細的技術(shù)教學(xué):
(圖片來(lái)源(′?_?`)網(wǎng)絡(luò ),侵刪)1、時(shí)間確保已經(jīng)安裝了matplotlib庫,何畫(huà)如果??沒(méi)有安ヽ(′?`)ノ裝,時(shí)間可以使用以(°□°)下命令進(jìn)行安裝:
pip install matplotlib
2、何(╯°□°)╯︵ ┻━┻畫(huà)導??入所需的(de)時(shí)間庫:
import matplotlib.pyplot as pltimport numpy as np
3、準備數據,何畫(huà)這里我們創(chuàng )??建一個(gè)簡(jiǎn)單的時(shí)(′▽?zhuān)?間數據集,包含日期和對應的何畫(huà)數值:??
dates = ['20200101', '2(′?_?`)020010??2', '20200103', '20??200104'ヽ(′?`)ノ, '20200105']values = [1, 3, 7, 2, 6]4、將日期轉換為matplotlib可以識別的時(shí)間格式,這里我ヽ(′ー`)ノ們使用matplotlib.dates(′?`)模塊中的何畫(huà)datestr2num函數將日期字符串轉換為數字:
from mat(′?_?`)plotlib.dates import dat(°o°)estr2numdate_nums = [datestr2num(date) for date in dates]
5、創(chuàng )建一個(gè)圖形??和一個(gè)子圖:
fig,時(shí)間 ax = plt.subplots()6、繪制折線(xiàn)圖,何畫(huà)這里我們使??用ax.plot函數繪制折線(xiàn)圖,并設置線(xiàn)條的顏色、粗細等屬??性:
ax.plot(date_nums, values, color='blu(′?`*)e', linewidth=2)
7、設置x軸和y軸的標簽:
ax.set_xlabel('Date')ax.set_ylabel('Value')8、設置x軸的時(shí)間格式,這里我們使用matplotlヽ(′?`)ノib.dates模塊中的DateFormatter類(lèi)來(lái)設置時(shí)間格式:
from matplotlib.dates import DateFormatterformatter = Da(?_?;)teFormatter('%Y%m%d')ax.xaxis.set_major_formatter(formatter)9、添加標題:
ax.set_title('Timeline')10、顯示網(wǎng)格線(xiàn):
ax.grid(True)
11、自動(dòng)調整圖形大小以適應數據:
plt.au( ?ヮ?)tos??cale(enable=True, axis='both', tig┐(′?`)┌ht=True)
12、顯示圖形:
plt.show()
將以上代碼整合到一起,完整的示例代碼如下:
import matplotlib.pyplot as pltimport numpy as npfrom matplot(′?_?`)lib.da??tes import datestr2num, DateFormatter準備數據dates = ['20200101', '20200102'(′ω`), '20200103', '20200104', '20200105']values = [1, 3, 7, 2, 6]date_nums = [datestr2num(date) for date in date(╬ ò﹏ó)s]創(chuàng )建圖形和子圖fig, ax = plt.su??bplots()繪制?折線(xiàn)圖ax.plot(date_nums, values, color='blue', linewidth=2)設置x軸和y軸的標簽ax.set_xヽ(′▽?zhuān)?ノlabel('Date')ax.set_ylabel('Value')設置x軸的時(shí)間格式formatter = DateFormatter('%Y%m%d')ax.xaxis.set_major_formatter(formatter)添加標題和顯示網(wǎng)格線(xiàn)、自動(dòng)調整圖形大小、顯示圖形等操作與之前的示(shi)例相同,不再重復。
