我是Python初学者。我正在尝试使用 Matplotlib.pyplot 绘制基本时间与发电量图。我将 date_time 输入数据从字符串转换为日期时间对象。当我绘制它时,“时间”部分丢失了。我想要 xticks 中的整个日期和时间部分。
import matplotlib.dates as mdates
fig , ax1 = plt.subplots()
xfmt = mdates.DateFormatter('%d-%m-%y\n%H:%M:%S')
ax1.xaxis.set_major_formatter(xfmt)
ax1.plot(date_time, generation)
fig.autofmt_xdate()
plt.grid()
上面的代码给出了下面的图表[在此处输入图像描述]
(https://i.sstatic.net/Mmbd8dpB.png)
x 轴中的“date_time”列具有以下数据作为样本
3 2024-03-01 00:04:05 14 2024-03-01 22:20:30 13 2024-03-02 03:56:23 16 2024-03-03 22:33:51 10 2024-03-04 14:46:24 31 2024-03-04 20:48:52 29 2024-03-05 01:31:23 4 2024-03-07 23:21:16
请帮我打印 x 轴上的日期和时间部分。谢谢你
您可以使用 set_xticks() 并将数据列表(日期时间)作为参数传递。 也许您会使用 autofmt_xdate(rotation=45) 旋转日期标签以获得更好的可读性。
这是修改后的代码:
import matplotlib.dates as mdates
fig , ax1 = plt.subplots()
xfmt = mdates.DateFormatter('%d-%m-%y\n%H:%M:%S')
ax1.xaxis.set_major_formatter(xfmt)
ax1.set_xticks(date_time) # Set x-axis ticks exactly at the date_time points
ax1.plot(date_time, generation)
fig.autofmt_xdate(rotation=45) # Rotate the date as you like
fig.autofmt_xdate()
plt.grid()