在Matplotlib中使用日期时间作为刻度 [英] Using datetime as ticks in Matplotlib
问题描述
我基本上是想绘制一个图形,其中x轴表示一年中的月份.数据存储在numpy.array中,尺寸为k x months
.这里是一个最小的例子(我的数据不是那么疯狂):
I'm basically trying to plot a graph where the x axis represent the month of the year. The data is stored in a numpy.array, with dimensions k x months
. Here it follows a minimal example (my data is not this crazy):
import numpy
import matplotlib
import matplotlib.pyplot as plt
cmap = plt.get_cmap('Set3')
colors = [cmap(i) for i in numpy.linspace(0, 1, len(complaints))]
data = numpy.random.rand(18,12)
y = range(data.shape[1])
plt.figure(figsize=(15, 7), dpi=200)
for i in range(data.shape[0]):
plt.plot(y, data[i,:], color=colors[i], linewidth=5)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.xticks(numpy.arange(0, 12, 1))
plt.xlabel('Hour of the Day')
plt.ylabel('Number of Complaints')
plt.title('Number of Complaints per Hour in 2015')
我想将xticks
作为字符串而不是数字.我想知道是否必须手动创建字符串列表,或者是否有另一种方法将数字翻译为月.例如,我必须在工作日做同样的事情.
I'd like to have the xticks
as strings instead of numbers. I'm wondering if I have to create a list of strings, manually, or if there is another way to translate the numbers to months. I have to do the same for weekdays, for example.
我一直在寻找这些例子:
I've been looking to these examples:
http://matplotlib.org/examples/pylab_examples/finance_demo.html http://matplotlib.org/examples/pylab_examples/date_demo2.html
但是我没有使用datetime
.
推荐答案
这是另一种绘图方法plot_date
,如果您的自变量类似于datetime
,则可能要使用该方法,而不是使用更通用的plot
方法:
This is an alternative plotting method plot_date
, which you might want to use if your independent variable are datetime
like, instead of using the more general plot
method:
import datetime
data = np.random.rand(24)
#a list of time: 00:00:00 to 23:00:00
times = [datetime.datetime.strptime(str(i), '%H') for i in range(24)]
#'H' controls xticklabel format, 'H' means only the hours is shown
#day, year, week, month, etc are not shown
plt.plot_date(times, data, fmt='H')
plt.setp(plt.gca().xaxis.get_majorticklabels(),
'rotation', 90)
这样做的好处是,现在您可以轻松控制xticks的密度,如果我们希望每小时打一次勾,我们将在plot_date
之后插入这些行:
The benefit of it is that now you can easily control the density of xticks, if we want to have a tick every hour, we will insert these lines after plot_date
:
##import it if not already imported
#import matplotlib.dates as mdates
plt.gca().xaxis.set_major_locator(mdates.HourLocator())
这篇关于在Matplotlib中使用日期时间作为刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!