簡體   English   中英

如何在matplotlib中設置日期的xticklabels

[英]How to set the xticklabels for date in matplotlib

我試圖從兩個列表中繪制值。 x軸值是日期。 到目前為止嘗試過這些事情

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]

dates = [datetime.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]

fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)

line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')

yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);

axes.set_xticks(dates)
#axes.set_xticklabels()

這個數字似乎很好。 但是無法正確標記x軸。 我試圖用2007-01-02或2007年1月的標簽來標記x軸。

提前致謝

您可以使用DateFormater控制日期的格式:

import matplotlib.dates as mdates
xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)

import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]

dates = [DT.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]

fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)

line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')

yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);

xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)
axes.set_xticks(dates)
plt.xticks(rotation=25)
plt.show()

產量

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM