简体   繁体   English

在 matplotlib 上用 x 轴上的日期绘制图形仅显示一些日期

[英]Plotting a graph on matplotlib with dates on x axis only shows some of the dates

I have 2 arrays:我有 2 个数组:


 dates = [datetime.date(2019, 12, 9), datetime.date(2019, 12, 10),
       datetime.date(2019, 12, 12), datetime.date(2019, 12, 13),
       datetime.date(2019, 12, 14), datetime.date(2019, 12, 15),
       datetime.date(2019, 12, 16), datetime.date(2019, 12, 17),
       datetime.date(2019, 12, 18), datetime.date(2019, 12, 19)]

counts = [10, 2, 48067, 49791, 35347, 39418, 38817, 34269, 28066,
       22212]

I am trying to create a graph that will show each of the dates, but only getting a few我正在尝试创建一个图表来显示每个日期,但只得到几个

plt.figure(figsize=(100,10))

fig.tight_layout()
plt.xticks(rotation=90)

plt.plot(dates, counts)


plt.show()

I have tried following this but I still had the same results - not getting all the dates on the x axis我试过按照这个,但我仍然有相同的结果 - 没有得到 x 轴上的所有日期

After you plot your graph, you can create a DateLocator and DateFormatter to change the format and frequency of the x ticks.绘制图形后,您可以创建DateLocatorDateFormatter来更改 x 刻度的格式和频率。 The full code with comments is below.带有注释的完整代码如下。

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

dates = [datetime.date(2019, 12, 9), datetime.date(2019, 12, 10),
         datetime.date(2019, 12, 12), datetime.date(2019, 12, 13),
         datetime.date(2019, 12, 14), datetime.date(2019, 12, 15),
         datetime.date(2019, 12, 16), datetime.date(2019, 12, 17),
         datetime.date(2019, 12, 18), datetime.date(2019, 12, 19)]

counts = [10, 2, 48067, 49791, 35347, 39418, 38817, 34269, 28066, 22212]


plt.figure(figsize=(100,10))
fig.tight_layout()
plt.xticks(rotation=90)
plt.plot(dates, counts)

ax=plt.gca()
# Find the days in the data
days = mdates.DayLocator()
# Format the days in the data
days_fmt = mdates.DateFormatter('%D')
# Set xaxis to use the day locator
ax.xaxis.set_major_locator(days)
# Set xaxis to use the day formatter
ax.xaxis.set_major_formatter(days_fmt)

plt.show()

This produces the following graph where all days are displayed with separate ticks.这将生成以下图表,其中所有日期都以单独的刻度显示。

在此处输入图片说明

For a detailed example with more date formats, check out this sample .有关更多日期格式的详细示例,请查看此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM