matplotlib命令與格式之tick坐標(biāo)軸日期格式(設(shè)置日期主副刻度)
1.橫坐標(biāo)設(shè)置時(shí)間格式
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# 配置橫坐標(biāo)為日期格式
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
例子:
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
# 生成橫縱坐標(biāo)信息
dates = ['01/02/1991', '01/03/1991', '01/04/1991']
xs = [datetime.strptime(d, '%m/%d/%Y').date() for d in dates]
ys = range(len(xs))
# 配置橫坐標(biāo)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
# Plot
plt.plot(xs, ys)
plt.gcf().autofmt_xdate() # 自動旋轉(zhuǎn)日期標(biāo)記
plt.show()
2.設(shè)置日期坐標(biāo)軸主副刻度值
所有坐標(biāo)軸日期格式類型
MinuteLocator: locate minutes(f)
HourLocator: locate hours
DayLocator: locate specified days of the month
WeekdayLocator: Locate days of the week, e.g., MO, TU
MonthLocator: locate months, e.g., 7 for july
YearLocator: locate years that are multiples of base
RRuleLocator: locate using a matplotlib.dates.rrulewrapper. The rrulewrapper is a simple wrapper around adateutil.rrule (dateutil) which allow almost arbitrary date tick specifications. See rrule example.
AutoDateLocator: On autoscale, this class picks the best MultipleDateLocator to set the view limits and the tick locations.
(1)獲取坐標(biāo)軸日期格式類型
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY #獲取每月一日數(shù)據(jù) monthdays = MonthLocator() #獲取每周一的日期數(shù)據(jù) mondays = WeekdayLocator(MONDAY) #獲取每日數(shù)據(jù) alldays = DayLocator() # import constants for the days of the week from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU # tick on mondays every week loc = WeekdayLocator(byweekday=MO, tz=tz) # tick on mondays and saturdays loc = WeekdayLocator(byweekday=(MO, SA)) # tick on mondays every second week loc = WeekdayLocator(byweekday=MO, interval=2) # tick every 5th easter(每隔5個選1個) rule = rrulewrapper(YEARLY, byeaster=1, interval=5) loc = RRuleLocator(rule)
(2)設(shè)置坐標(biāo)軸日期格式
#設(shè)置主副刻度
ax.xaxis.set_major_locator(mondays)ax.xaxis.set_minor_locator(alldays)
#設(shè)置坐標(biāo)軸刻度標(biāo)簽格式
mondayFormatter = DateFormatter('%Y-%m-%d') # 如:2-29-2015dayFormatter = DateFormatter('%d') # 如:12ax.xaxis.set_major_formatter(mondayFormatter)
#字符串旋轉(zhuǎn)
for label in ax1.get_xticklabels(): label.set_rotation(30) label.set_horizontalalignment('right')
(3)例子
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
#銷售數(shù)據(jù)
dates=[20171101,20171102,20171103,20171104]
sales=[102.1,100.6,849,682]
#將dates改成日期格式
x= [datetime.strptime(str(d), '%Y%m%d').date() for d in dates]
#figure布局
fig=plt.figure(figsize=(8,4))
ax1=fig.add_subplot(1,1,1)
#繪圖
ax1.plot(x,y,ls='--',lw=3,color='b',marker='o',ms=6, mec='r',mew=2, mfc='w',label='業(yè)績趨勢走向')
plt.gcf().autofmt_xdate() # 自動旋轉(zhuǎn)日期標(biāo)記
#設(shè)置x軸主刻度格式
alldays = mdates.DayLocator() #主刻度為每天
ax1.xaxis.set_major_locator(alldays) #設(shè)置主刻度
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y%m%d'))
#設(shè)置副刻度格式
hoursLoc = mpl.dates.HourLocator(interval=6) #為6小時(shí)為1副刻度
ax1.xaxis.set_minor_locator(hoursLoc)
ax1.xaxis.set_minor_formatter(mdates.DateFormatter('%H'))
#參數(shù)pad用于設(shè)置刻度線與標(biāo)簽間的距離
ax1.tick_params(pad=10)
#顯示圖像
plt.show()

3.設(shè)置日期時(shí)間刻度值
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import datetime as dt
fig = plt.figure()
ax2 = fig.add_subplot(212)
date2_1 = dt.datetime(2008,9,23)
date2_2 = dt.datetime(2008,10,3)
delta2 = dt.timedelta(days=1)
dates2 = mpl.dates.drange(date2_1, date2_2, delta2)
y2 = np.random.rand(len(dates2))
ax2.plot_date(dates2, y2, linestyle='-')
dateFmt = mpl.dates.DateFormatter('%Y-%m-%d')
ax2.xaxis.set_major_formatter(dateFmt)
daysLoc = mpl.dates.DayLocator()
hoursLoc = mpl.dates.HourLocator(interval=6)
ax2.xaxis.set_major_locator(daysLoc)
ax2.xaxis.set_minor_locator(hoursLoc)
fig.autofmt_xdate(bottom=0.18)
fig.subplots_adjust(left=0.18)
ax1 = fig.add_subplot(211)
date1_1 = dt.datetime(2008, 9, 23)
date1_2 = dt.datetime(2009, 2, 16)
delta1 = dt.timedelta(days=10)
dates1 = mpl.dates.drange(date1_1, date1_2, delta1)
y1 = np.random.rand(len(dates1))
ax1.plot_date(dates1, y1, linestyle='--')
monthsLoc = mpl.dates.MonthLocator()
weeksLoc = mpl.dates.WeekdayLocator()
ax1.xaxis.set_major_locator(monthsLoc)
ax1.xaxis.set_minor_locator(weeksLoc)
monthsFmt = mpl.dates.DateFormatter('%b')
ax1.xaxis.set_major_formatter(monthsFmt)
plt.show()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解運(yùn)行Python的神器Jupyter Notebook
如果我們想要運(yùn)行Python,就是在Python或者IPython的解釋器環(huán)境中進(jìn)行交互式運(yùn)行,或者程序員最喜歡的編寫.py文件,在文件中編寫python代碼,然后運(yùn)行。如果想寫一篇Python的文章,里面有代碼,還希望代碼在當(dāng)前頁面運(yùn)行,那就是使用我們今天要介紹的Jupyter Notebook。2021-06-06
通過Python實(shí)現(xiàn)Payload分離免殺過程詳解
這篇文章主要介紹了通過Python實(shí)現(xiàn)Payload分離免殺過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
基于Python利用Pygame實(shí)現(xiàn)翻轉(zhuǎn)圖像
這篇文章主要介紹了基于Python利用Pygame實(shí)現(xiàn)翻轉(zhuǎn)圖像,我們將了解如何使用Pygame翻轉(zhuǎn)圖像,要翻轉(zhuǎn)圖像,我們需要使用pygame.transform.flip(Surface,?xbool,?ybool)?方法,該方法被調(diào)用來根據(jù)我們的需要在垂直方向或水平方向翻轉(zhuǎn)圖像,下面來看看具體的實(shí)現(xiàn)過程吧2022-02-02
Django Admin后臺添加數(shù)據(jù)庫視圖過程解析
這篇文章主要介紹了Django Admin后臺添加數(shù)據(jù)庫視圖過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Python中的http.server庫用法詳細(xì)介紹
這篇文章主要給大家介紹了關(guān)于Python中http.server庫用法的相關(guān)資料,http.server是Python標(biāo)準(zhǔn)庫中的一個模塊,用于創(chuàng)建基本的HTTP服務(wù)器,它提供了處理HTTP請求的基本框架和核心類,需要的朋友可以參考下2024-11-11

