Matplotlib pyplot - 刻度控制和显示日期

Fre*_*Fre 7 python matplotlib

我的matplotlib pyplot太多了xticks- 它目前显示 15 年期间的每一年和每月,例如“2001-01”,但我只希望 x 轴显示年份(例如 2001)。

输出将是一个折线图,其中 x 轴显示日期,y 轴显示销售和租金价格。

# Defining the variables
ts1 = prices['Month'] # eg. "2001-01" and so on
ts2 = prices['Sale'] 
ts3 = prices['Rent'] 

# Reading '2001-01' as year and month
ts1 = [dt.datetime.strptime(d,'%Y-%m').date() for d in ts1]

plt.figure(figsize=(13, 9))
# Below is where it goes wrong. I don't know how to set xticks to show each year. 
plt.xticks(ts1, rotation='vertical')
plt.xlabel('Year')
plt.ylabel('Price')
plt.plot(ts1, ts2, 'r-', ts1, ts3, 'b.-')
plt.gcf().autofmt_xdate()
plt.show()
Run Code Online (Sandbox Code Playgroud)

Pyt*_*ogy 5

您可以使用plt.xticks.

例如,这里我将 xticks 频率设置为每三个索引显示一次。在您的情况下,您可能希望每十二个索引执行一次。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.random.randn(10)

plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 3))
plt.show()
Run Code Online (Sandbox Code Playgroud)

在您的情况下,由于您使用的是日期,因此您可以将上面倒数第二行的参数替换为类似的内容ts1[0::12],这将选择每个第 12 个元素,ts1或者np.arange(0, len(dates), 12)选择与您要显示的刻度相对应的每个第 12 个索引。


Ffi*_*ydd 5

尝试plt.xticks完全删除函数调用。matplotlib 然后将使用默认AutoDateLocator函数来查找最佳刻度位置。

或者,如果默认值包括一些您不想要的月份,那么您可以使用matplotlib.dates.YearLocator这将强制刻度为年。

您可以在一个快速示例中设置定位器,如下所示:

import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import numpy as np
import datetime as dt

x = [dt.datetime.utcnow() + dt.timedelta(days=i) for i in range(1000)]
y = range(len(x))

plt.plot(x, y)

locator = mdate.YearLocator()
plt.gca().xaxis.set_major_locator(locator)

plt.gcf().autofmt_xdate()

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明