本人是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?。?!