【關(guān)于《Python從入門到實踐》書中第16章的作圖問題】python使用matplotlib作圖:如何合理設(shè)置x軸日期格式

本人是Python語言初學(xué)者。因在閱讀《Python從入門到實踐》一書的第十六章的實踐過程中,發(fā)現(xiàn)按書中示例代碼所做的圖形與書中所示圖形不符:X軸的日期顯示不符(fig.autofmt_xdate()無法實現(xiàn)合理設(shè)置X軸日期格式)。

? ? ? 故有此文。


書中代碼所得的圖形。

? ? ? 百度找到一種方法,通過fig.add_subplot(1,1,1)在圖形原位置重新編輯設(shè)置X軸的格式。

索引:Matplotlib繪圖雙縱坐標軸設(shè)置及控制設(shè)置時間格式

? ? ? 本方法除書中用到的csv和datetime庫,還需要下面的:

importmatplotlib.pyplotasplt

importmatplotlib.datesasmdate

importpandasaspd

? ? ? 首先在原位值設(shè)置一個新的圖形(變量名不一定ax):

fig = plt.figure(figsize=(10,6))

ax = fig.add_subplot(1,1,1)

ax = fig.add_subplot(1,1,1)


? ? ? 然后,設(shè)置x軸的格式為[%b:月份英文縮寫] [%Y:年份]:


plt.xlabel(' ',fontsize=16)

ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y'))

ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y'))

? ? ? 之后,設(shè)置x軸刻度范圍,這里要用到pandas庫(簡寫pd):

plt.xlabel(' ',fontsize=16)

ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y'))

plt.xticks(pd.date_range('2014-01','2014-12',freq='MS'),rotation=30)# freq='MS',設(shè)置刻度格式為每月的開始(month start frequency)

plt.xticks(pd.date_range('2014-01','2014-12',freq='MS'),rotation=30) # freq='MS',設(shè)置刻度格式為每月的開始(month start frequency)

關(guān)于pandas.date_range()中freq設(shè)置方法,見:pandas-date_range(freq)

? ? ? 經(jīng)過上述代碼修改,現(xiàn)在的代碼為(示例代碼為書中第十六章習(xí)題16-2,多了個兩地天氣對比):

# -*- coding:utf-8 -*-

"""

Death Valley and Sitka

temperatures:highs and lows

@auther:Wangsheng

"""

importcsv

fromdatetimeimportdatetime

importmatplotlib.pyplotasplt

importmatplotlib.datesasmdate

importpandasaspd

filename1 ='death_valley_2014.csv'

withopen(filename1)asf_obj:

? ? reader = csv.reader(f_obj)

? ? header_row = next(reader)

? ? dates_D,highs_D,lows_D = [ ], [ ],[ ]

forrowinreader:

try:

current_date = datetime.strptime(row[0],'%Y-%m-%d')

high = int(row[1])

low = int(row[3])

exceptValueError:

print(current_date,"missing data")

else:

? ? ? ? ? ? dates_D.append(current_date)

? ? ? ? ? ? highs_D.append(high)

? ? ? ? ? ? lows_D.append(low)


filename2 ='sitka_weather_2014.csv'

withopen(filename2)asf_obj:

? ? reader = csv.reader(f_obj)

? ? header_row = next(reader)

? ? dates_S,highs_S,lows_S = [ ], [ ],[ ]

forrowinreader:

try:

current_date = datetime.strptime(row[0],'%Y-%m-%d')

high = int(row[1])

low = int(row[3])

exceptValueError:

print(current_date,"missing data")

else:

? ? ? ? ? ? dates_S.append(current_date)

? ? ? ? ? ? highs_S.append(high)

? ? ? ? ? ? lows_S.append(low)

# 根據(jù)數(shù)據(jù)繪制圖形

fig = plt.figure(figsize=(10,6))

ax = fig.add_subplot(1,1,1)

plt.plot(dates_D,highs_D,label='Death Valley highs',c='red',alpha=0.5)# alpha設(shè)置line的透明度0~1,0為完全透明

plt.plot(dates_D,lows_D,label='Death Valley lows',c='blue',alpha=0.5)

plt.plot(dates_S,highs_S,label='Sitka highs',c='red',alpha=0.3)

plt.plot(dates_S,lows_S,label='Sitka lows',c='blue',alpha=0.3)

plt.fill_between(dates_D,highs_D,lows_D,facecolor='blue',alpha=0.2)

plt.fill_between(dates_S,highs_S,lows_S,facecolor='blue',alpha=0.15)

# 設(shè)置圖形的格式

plt.title('Daily high and low temperatures - 2014\nDeath Valley and Sitka, CA',fontsize=20)

#設(shè)置x軸日期格式

plt.xlabel(' ',fontsize=16)

ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y'))

plt.xticks(pd.date_range('2014-01','2014-12',freq='MS'),rotation=30)

plt.ylabel("Temperature ( F )",fontsize=16)

plt.ylim([0,120])# 設(shè)置y軸刻度范圍

plt.tick_params(axis='both',which='major',labelsize=16)

plt.legend()# 用于顯示諸如plt.plot(dates_S,highs_S,label='Sitka highs',c='red',alpha=0.3)中的label標簽

plt.show()


? ? ? 希望對你有幫助。

公眾號:勝言

個人博客:wangsheng.tech

關(guān)注和我一起學(xué)python?。?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容