gpt4 book ai didi

python - 如何每小时获取蜱虫

转载 作者:太空狗 更新时间:2023-10-29 18:00:42 25 4
gpt4 key购买 nike

考虑这个简单的例子

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates

pd.__version__
Out[147]: u'0.22.0'

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')

df = pd.Series(np.random.randn(len(idx)), index = idx)
df.head()
Out[145]:
2017-01-01 05:03:00 0.4361
2017-01-01 05:04:00 0.9737
2017-01-01 05:05:00 0.8430
2017-01-01 05:06:00 0.4292
2017-01-01 05:07:00 0.5739
Freq: T, dtype: float64

我想绘制这个,每小时都有一次滴答声。我使用:

fig, ax = plt.subplots()
hours = mdates.HourLocator(interval = 1) #
h_fmt = mdates.DateFormatter('%H:%M:%S')

df.plot(ax = ax, color = 'black', linewidth = 0.4)

ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

给出

enter image description here

为什么滴答声不是每小时出现一次?感谢您的帮助!

最佳答案

问题是,虽然 pandas 通常直接包装 matplotlib 绘图方法,但对于带有日期的绘图,情况并非如此。一旦涉及到日期,pandas 就会使用完全不同的日期数字表示形式,因此也会使用自己的刻度定位器。

如果您想在使用 pandas 创建的绘图上使用 matplotlib.dates 格式化程序或定位器,您可以在 pandas 绘图中使用 x_compat=True 选项。

df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)

这允许使用 matplotlib.dates 格式化程序或定位器,如下所示。否则,您可以将 df.plot(ax = ax, color = 'black', linewidth = 0.4) 替换为

ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)

完整示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')
df = pd.Series(np.random.randn(len(idx)), index = idx)

fig, ax = plt.subplots()
hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M:%S')

ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)
#or use
df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)
#Then tick and format with matplotlib:
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

fig.autofmt_xdate()
plt.show()

enter image description here


如果在这里使用 pandas 的动机是(如以下评论所述)能够使用 secondary_y,则 matplotlib 图的等价物将是双轴 twinx。< p>

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')

df = pd.DataFrame(np.cumsum(np.random.randn(len(idx), 2),0),
index = idx, columns=list("AB"))

fig, ax = plt.subplots()
ax.plot(df.index, df["A"], color = 'black')
ax2 = ax.twinx()
ax2.plot(df.index, df["B"], color = 'indigo')

hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

fig.autofmt_xdate()
plt.show()

enter image description here

关于python - 如何每小时获取蜱虫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48790378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com