[英]How can I select the temporal resolution of my datetime x-ticks in my matplotlib pyplot plot?
I am currently plotting a temporal series using pyplot
.我目前正在使用pyplot
绘制时间序列。 I have specified the following x-ticks, which consist of four objects of type datetime
:我指定了以下 x-ticks,它由四个datetime
类型的对象组成:
x_ticks
array(['2021-10-17T09:23:11.000000', '2021-10-17T10:02:15.750000',
'2021-10-17T10:41:20.500000', '2021-10-17T11:20:25.250000'],
dtype='datetime64[us]')
As you can see, each element (purposely) has a time resolution down to microseconds.如您所见,每个元素(有意地)具有低至微秒的时间分辨率。 So far, so good.到目前为止,一切都很好。 However, when I actually get to plot my graph of interest, by default the time axis appears with format YYYY-MM-DD, like in the image below:但是,当我真正开始绘制我感兴趣的图表时,默认情况下,时间轴以 YYYY-MM-DD 格式显示,如下图所示:
It automatically crops the hours and seconds, but I would like to visualize them.它会自动裁剪小时和秒,但我想将它们可视化。 How can I specify the resolution of my time x-ticks that needs to appear in the plots?如何指定需要出现在图中的时间 x 刻度的分辨率?
Use a DateFormatter to set the display of the axis.使用 DateFormatter 设置轴的显示。 I also used a LinearLocator to show not all labels, in this case it's 4. And rotated the labels to take up less space with autofmt_xdate().我还使用了 LinearLocator 来显示并非所有标签,在本例中为 4。并使用 autofmt_xdate() 旋转标签以占用更少的空间。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates
aaa = np.array(['2021-10-17T09:23:11.000000', '2021-10-17T10:02:15.750000',
'2021-10-17T10:41:20.500000', '2021-10-17T11:20:25.250000'],
dtype='datetime64[us]')
bbb = [1, 3, 7, 5]
fig, ax = plt.subplots()
ax.plot(aaa, bbb)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m-%d %H:%M:%S"))
locator = matplotlib.ticker.LinearLocator(4)
ax.xaxis.set_major_locator(locator)
fig.autofmt_xdate()
plt.show()
If subplots with captions are needed, although this was not visible in the question, then the solution is as follows:如果需要带有标题的子图,尽管这在问题中不可见,但解决方案如下:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import matplotlib.dates
fig, axs = plt.subplots(3, 1, constrained_layout=True, figsize=(7, 7))
aaa = np.array(['2021-10-17T09:23:11.000000', '2021-10-17T10:02:15.750000',
'2021-10-17T10:41:20.500000', '2021-10-17T11:20:25.250000'],
dtype='datetime64[us]')
bbb = [1, 3, 7, 5]
lims = aaa[0], aaa[-1]
form = matplotlib.dates.DateFormatter("%Y-%m-%d %H:%M:%S")
locator = matplotlib.ticker.LinearLocator(4)
for nn, ax in enumerate(axs):
ax.plot(aaa, bbb)
ax.set_xlim(lims)
ax.xaxis.set_major_formatter(form)
ax.xaxis.set_major_locator(locator)
for label in ax.get_xticklabels():
label.set_fontsize(7)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.