按照给定HERE的示例,我想创建一个只显示x轴上的时间而不是日期的曲线图.因此,我将示例代码修改为以下代码:

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.HourLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

但我得到的不是10:00到10:10的时间范围,而是:

enter image description here

怎么啦?

推荐答案

我认为有两个问题是,当你将.date()链接到.strptime(...)时,时间信息被丢弃了,第二,使用了HourLocator而不是MinuteLocator.

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M") for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)

#Comment out to show fewer minute ticks
locator = mdates.MinuteLocator()
ax.xaxis.set_major_locator(locator)

plt.plot(x_values, y_values, 'o-');

enter image description here

Python相关问答推荐

替换为Pandas

如何从不同长度的HTML表格中抓取准确的字段?

如何对行使用分段/部分.diff()或.pct_change()?

了解shuffle在NP.random.Generator.choice()中的作用

opencv Python稳定的图标识别

使用pandas、matplotlib和Yearbox绘制时显示错误的年份

计算相同形状的两个张量的SSE损失

多处理代码在while循环中不工作

我必须将Sigmoid函数与r2值的两种类型的数据集(每种6个数据集)进行匹配,然后绘制匹配函数的求导.我会犯错

acme错误-Veritas错误:模块收件箱没有属性linear_util'

Matlab中是否有Python的f-字符串等效物

根据在同一数据框中的查找向数据框添加值

标题:如何在Python中使用嵌套饼图可视化分层数据?

Python库:可选地支持numpy类型,而不依赖于numpy

如何创建一个缓冲区周围的一行与manim?

Python—从np.array中 Select 复杂的列子集

如何并行化/加速并行numba代码?

在单次扫描中创建列表

如何在PySide/Qt QColumbnView中删除列

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?