在独立轴上绘制时间

发布于 2024-08-08 02:38:07 字数 173 浏览 2 评论 0原文

我有一个格式为 (HH:MM:SS.mmmmmm) 的时间戳数组和另一个浮点数数组,每个数组对应于时间戳数组中的一个值。

我可以使用 Matplotlib 在 x 轴上绘制时间并在 y 轴上绘制数字吗?

我试图这样做,但不知何故它只接受浮点数数组。我怎样才能让它绘制时间?我必须以任何方式修改格式吗?

I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.

Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?

I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

郁金香雨 2024-08-15 02:38:07

更新

此答案已过时自 matplotlib 版本 3.5 起plot 函数现在直接处理日期时间数据。请参阅 https://matplotlib.org/3.5.1/api /_as_gen/matplotlib.pyplot.plot_date.html

不鼓励使用plot_date。该方法存在于历史
原因,并且将来可能会被弃用。

应使用plot直接绘制类似日期时间的数据。

如果您需要将纯数字数据绘制为 Matplotlib 日期格式或
需要设置时区,调用 ax.xaxis.axis_date / ax.yaxis.axis_date
在情节之前。请参阅 Axis.axis_date。


旧的、过时的答案:

您必须首先将时间戳转换为 Python datetime 对象(使用 datetime.strptime)。然后使用 date2num 将日期转换为 matplotlib 格式。

使用 plot_date 绘制日期和值

import matplotlib.pyplot as plt
import matplotlib.dates

from datetime import datetime

x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)]
y_values = [1.0, 3.0, 2.0]

dates = matplotlib.dates.date2num(x_values)
plt.plot_date(dates, y_values)

在此处输入图像描述

Update:

This answer is outdated since matplotlib version 3.5. The plot function now handles datetime data directly. See https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.plot_date.html

The use of plot_date is discouraged. This method exists for historic
reasons and may be deprecated in the future.

datetime-like data should directly be plotted using plot.

If you need to plot plain numeric data as Matplotlib date format or
need to set a timezone, call ax.xaxis.axis_date / ax.yaxis.axis_date
before plot. See Axis.axis_date.


Old, outdated answer:

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

import matplotlib.pyplot as plt
import matplotlib.dates

from datetime import datetime

x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)]
y_values = [1.0, 3.0, 2.0]

dates = matplotlib.dates.date2num(x_values)
plt.plot_date(dates, y_values)

enter image description here

忆梦 2024-08-15 02:38:07

您还可以使用 pyplot.plot (从字符串表示形式解析它们之后)。 (使用 matplotlib 版本 1.2.0 和 1.3.1 进行测试。)

示例:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

结果图像:

Line Plot


这里与散点图:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

生成与此类似的图像:

散点图

You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)

Example:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Resulting image:

Line Plot


Here's the same as a scatter plot:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Produces an image similar to this:

Scatter Plot

绅士风度i 2024-08-15 02:38:07

7 年后,这段代码对我很有帮助。
然而,我的时间仍然没有正确显示。

输入图像描述这里

使用 Matplotlib 2.0.0,我必须从 在 matplotlib 中编辑 x 轴刻度标签的日期格式 作者:Paul H。

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

我将格式更改为 (%H:%M) 并且时间显示正确。
输入图像描述这里

感谢社区。

7 years later and this code has helped me.
However, my times still were not showing up correctly.

enter image description here

Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

I changed the format to (%H:%M) and the time displayed correctly.
enter image description here

All thanks to the community.

甜妞爱困 2024-08-15 02:38:07

我在使用 matplotlib 版本时遇到了问题:2.0.2。运行上面的示例,我得到了一组居中堆叠的气泡。

graph with centered stack of bubble

我通过添加另一行“修复”了问题:

plt.plot([],[])

整个代码片段变为:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

这会产生一个气泡根据需要分布的图像。

随时间分布的气泡图

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

风启觞 2024-08-15 02:38:07

尚未提及 Pandas 数据框。我想展示这些如何解决我的日期时间问题。我的日期时间精确到毫秒2021-04-01 16:05:37。我正在从 /proc 中提取 linux/haproxy 吞吐量,这样我就可以按照自己喜欢的方式对其进行格式化。这对于将数据输入实时图形动画非常有用。

看一下 csv。 (忽略我在另一个图中使用的每秒数据包列)

head -2 ~/data
date,mbps,pps
2021-04-01 16:05:37,113,9342.00
...

通过使用 print(dataframe.dtype) 我可以看到数据是如何读入的:

(base) ➜  graphs ./throughput.py
date      object
mbps      int64
pps       float64
dtype:    object

Pandas 将日期字符串作为“对象” ",这只是 char 类型。在脚本中按原样使用此内容:

import matplotlib.pyplot as plt
import pandas as pd

dataframe = pd.read_csv("~/data")

dates = dataframe["date"]
mbps = dataframe["mbps"]

plt.plot(dates, mbps, label="mbps")
plt.title("throughput")
plt.xlabel("time")
plt.ylabel("mbps")
plt.legend()
plt.xticks(rotation=45)

plt.show()

在此处输入图像描述

Matplotlib 渲染所有毫秒时间数据。我添加了 plt.xticks(rotation=45) 来倾斜日期,但这不是我想要的。我可以将日期“对象”转换为 datetime64[ns]。哪个 matplotlib 确实知道如何渲染。

dataframe["date"] = pd.to_datetime(dataframe["date"]) 

这次我的日期类型为 datetime64[ns]

(base) ➜  graphs ./throughput.py
date    datetime64[ns]
mbps             int64
pps            float64
dtype:          object

相同的脚本,但有 1 行差异。

#!/usr/bin/env python
import matplotlib.pyplot as plt
import pandas as pd

dataframe = pd.read_csv("~/data")

# convert object to datetime64[ns]
dataframe["date"] = pd.to_datetime(dataframe["date"]) 

dates = dataframe["date"]
mbps = dataframe["mbps"]

plt.plot(dates, mbps, label="mbps")
plt.title("throughput")
plt.xlabel("time")
plt.ylabel("mbps")
plt.legend()
plt.xticks(rotation=45)

plt.show()

这可能不适合您的用例,但可能对其他人有帮助。

输入图片描述这里

Pandas dataframes haven't been mentioned yet. I wanted to show how these solved my datetime problem. I have datetime to the milisecond 2021-04-01 16:05:37. I am pulling linux/haproxy throughput from /proc so I can really format it however I like. This is nice for feeding data into a live graph animation.

Here's a look at the csv. (Ignore the packets per second column I'm using that in another graph)

head -2 ~/data
date,mbps,pps
2021-04-01 16:05:37,113,9342.00
...

By using print(dataframe.dtype) I can see how the data was read in:

(base) ➜  graphs ./throughput.py
date      object
mbps      int64
pps       float64
dtype:    object

Pandas pulls the date string in as "object", which is just type char. Using this as-is in a script:

import matplotlib.pyplot as plt
import pandas as pd

dataframe = pd.read_csv("~/data")

dates = dataframe["date"]
mbps = dataframe["mbps"]

plt.plot(dates, mbps, label="mbps")
plt.title("throughput")
plt.xlabel("time")
plt.ylabel("mbps")
plt.legend()
plt.xticks(rotation=45)

plt.show()

enter image description here

Matplotlib renders all the milisecond time data. I've added plt.xticks(rotation=45) to tilt the dates but it's not what I want. I can convert the date "object" to a datetime64[ns]. Which matplotlib does know how to render.

dataframe["date"] = pd.to_datetime(dataframe["date"]) 

This time my date is type datetime64[ns]

(base) ➜  graphs ./throughput.py
date    datetime64[ns]
mbps             int64
pps            float64
dtype:          object

Same script with 1 line difference.

#!/usr/bin/env python
import matplotlib.pyplot as plt
import pandas as pd

dataframe = pd.read_csv("~/data")

# convert object to datetime64[ns]
dataframe["date"] = pd.to_datetime(dataframe["date"]) 

dates = dataframe["date"]
mbps = dataframe["mbps"]

plt.plot(dates, mbps, label="mbps")
plt.title("throughput")
plt.xlabel("time")
plt.ylabel("mbps")
plt.legend()
plt.xticks(rotation=45)

plt.show()

This might not have been ideal for your usecase but it might help someone else.

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文