python - 如何在 Python 中的同一个图上绘制两个不同的间隔时间序列

标签 python matplotlib plot

我有两个不同的间隔时间序列,我想将它们绘制在同一个图表上。

两者都是12:30:00~1:25:00之间的系列,但时间顺序不同:一个是5秒,一个是10.3秒左右。这两个系列的类型都是“pandas.core.series.Series”。时间索引的类型是string,由strftime生成。 例如, A 系列将是:

12:30:05    0.176786
12:30:15    0.176786
12:30:26    0.176786
...
13:22:26    0.002395
13:22:37    0.002395
13:22:47    0.001574

B 系列将是:

12:30:05    0.140277
12:30:10    0.140277
12:30:15    0.140277
...
13:24:20    0.000642
13:24:25    0.000642
13:24:30    0.000454

我试图通过以下方式将两个系列绘制在同一个图上:

import matplotlib.pyplot as plt
A.plot()
B.plot()
plt.gcf().autofmt_xdate()
plt.show()

它是这样工作的:

enter image description here

很明显,第一张图中的蓝线在 12:55:05 左右消失了,因为系列 A 只有 B 的一半 x 点,而 plot() 仅根据 x 轴的顺序排列绘图,而不是时间间隔。

如果我单独绘制系列 A 会很清楚:

enter image description here

我想要的是让两个系列显示在同一个图中并根据真实时间间隔排列。理想情况下,情节应该类似于:

enter image description here

我希望我已经表达清楚了。如果有任何混淆,请告诉我。

最佳答案

这是直接创建日期时间,而不是将它们转换为字符串;根据您的原始格式,您可能需要 matplotlib.dates.datestr2num。然后它们被转换为 matplotlib 的日期时间表示。这看起来很麻烦,但意味着间距有时是正确的。

import matplotlib.pyplot as plt
from matplotlib.dates import date2num , DateFormatter
import datetime as dt

 # different times from the same timespan
TA = map(lambda x: date2num(dt.datetime(2015, 6, 15, 12, 1, x)),
         range(1, 20, 5))
TB = map(lambda x: date2num(dt.datetime(2015, 6, 15, 12, 1, x)),
         range(1, 20, 3))
A = [1.2, 1.1, 0.8, 0.66]
B = [1.3, 1.2, 0.7, 0.5, 0.45, 0.4, 0.3]

fig, ax = plt.subplots()
ax.plot_date(TA, A, 'b--')
ax.plot_date(TB, B, 'g:')
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
plt.show()

enter image description here

关于python - 如何在 Python 中的同一个图上绘制两个不同的间隔时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868707/

相关文章:

python - Matplotlib 文本对齐

python - Django channel 的负载尖峰保护

python - Pygame:放置多个对象时出错:(

matplotlib - 将 GridSpec 与自定义 wspace 一起使用不适用于 tight_layout

Python - 使用 Matplotlib 绘制散点图时出错 : Index out of range

c++ - 如何使用 FFTW3/QWT 绘制频谱?

python - Windows 上的ezyang/git-ftp

python - IPython 和 matplotlib 配置文件和文件

python - matplotlib 在 while 循环中更新绘图,以日期为 x 轴

python - Matplotlib 返回一个绘图对象