Matplotlib xaxis重叠使用时间字符串

2024-09-21 05:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从以下数据创建绘图:

timeArray= ['11:47:46.585', '11:47:46.695', '11:47:46.805', '11:47:46.915', '11:47:47.025', '11:47:47.135', '11:47:47.245', '11:47:47.355', '11:47:47.465', '11:47:47.575', '11:47:47.685', '11:47:47.795', '11:47:47.905', '11:47:48.015', '11:47:48.125', '11:47:48.235', '11:47:48.345', '11:47:48.455', '11:47:48.565', '11:47:48.675', '11:47:48.785', '11:47:48.895', '11:47:49.005', '11:47:49.115', '11:47:49.225', '11:47:49.335', '11:47:49.445', '11:47:49.555', '11:47:49.665', '11:47:49.775', '11:47:49.885', '11:47:49.995', '11:47:50.105', '11:47:50.215', '11:47:50.325', '11:47:50.435', '11:47:50.545', '11:47:50.655', '11:47:50.765', '11:47:50.875', '11:47:50.985', '11:47:51.095', '11:47:51.205', '11:47:51.315', '11:47:51.425', '11:47:51.535', '11:47:51.645', '11:47:51.755', '11:47:51.865', '11:47:51.975', '11:47:52.085', '11:47:52.195', '11:47:52.305', '11:47:52.415']

valueArray = [10382.0, 8372.0, 11117.0, 11804.0, 10164.0, 10221.0, 10488.0, 7910.0, 12911.0, 11422.0, 15361.0, 15424.0, 10629.0, 14993.0, 13827.0, 15164.0, 10514.0, 10356.0, 14638.0, 12272.0, 14980.0, 14391.0, 12984.0, 18967.0, 15792.0, 14753.0, 16205.0, 19187.0, 13922.0, 10787.0, 14500.0, 12918.0, 13985.0, 14695.0, 14014.0, 12087.0, 12163.0, 11424.0, 8598.0, 8573.0, 9986.0, 10315.0, 11449.0, 9146.0, 11160.0, 6861.0, 10211.0, 9097.0, 8443.0, 5446.0, 6354.0, 6829.0, 5786.0, 7860.0]

timeArray将是x轴,valueArray将是y轴。在

绘图线如下:

^{pr2}$

我得到了这张图:overlap time axis

我已经用过:plt.gcf().autofmt_xdate(),但仍有一次超过下一次。在

我也尝试过:

xaxis = np.linspace(min(timeArray),max(timeArray), 10)
plt.xticks(xaxis) 

但我得到了typeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

有没有一种简单的方法可以保持数据的原样,但不必每次都以微秒显示?在


Tags: 数据绘图timepltgcfdtypeoverlapaxis
2条回答

我建议您将时间转换为datetime对象而不是字符串,然后使用matplotlib.mdates.DateFormatter()和适当的日期格式:

import matplotlib.dates as mdates
import datetime

fmt = mdates.DateFormatter('%H:%M:%S')
timeArray = [datetime.datetime.strptime(i, '%H:%M:%S.%f') for i in timeArray]

fig, ax = plt.subplots()

plt.plot(timeArray,valueArray,'r', label='values over time')
ax.xaxis.set_major_formatter(fmt)

结果是:

enter image description here

您可以这样做:

 import datetime
 import matplotlib.pyplot as plt
 import pandas as pd

 timeArray = pd.to_datetime(pd.Series(timeArray))
 plt.plot(timeArray,valueArray,'r', label='values over time')
 plt.show()

输出:enter image description here

或者给记号添加一些旋转:

^{pr2}$

enter image description here

相关问题 更多 >

    热门问题