Python 如何每小时获得滴答声?

Python 如何每小时获得滴答声?,python,pandas,matplotlib,Python,Pandas,Matplotlib,考虑这个简单的例子 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

考虑这个简单的例子

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)


为什么这里的蜱虫不是每小时出现一次?谢谢你的帮助

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

如果要在使用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()


如果此处使用pandas的动机(如以下评论所述)是为了能够使用
secondary_y
,则matplotlib绘图的等效物将是双轴
twinx

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()

仅含熊猫的解决方案 您可以使用
DatetimeIndex
的时间戳设置每小时的刻度。可以通过利用时间戳的优势来创建刻度

import numpy as np   # v 1.19.2
import pandas as pd  # v 1.1.3

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

ax = series.plot(color='black', linewidth=0.4, figsize=(10,4))
ticks = series.index[series.index.minute == 0]
ax.set_xticks(ticks)
ax.set_xticklabels(ticks.strftime('%H:%M'));

你应该玩
xtick
。你知道怎么玩吗?谢谢@ℕʘʘḆḽḘ: 所以你想要的输出只是在每一整小时看到尖峰?可能相关:@Skandix,是的,我想看到的不仅是8,10,12的尖峰,而且是每小时6,7,8,9,10等的尖峰。也许让Pandas继续绘制的一个解决方法是获得一个常规的时间戳索引,而不是Pandas datetime?我想保留Pandas构造函数,因为我广泛使用plot的
secondary_y
参数来显示多个时间序列……我无法想象有任何解决方法<代码>matplotlib.dates假定数字轴表示自0001-01-01 UTC起的天数,加上1。仅当轴使用此日期时间格式时,它才会正确地勾选并标记轴。另一方面,熊猫将根据数据创建其轴单位,并为这些单位使用适当的定位器。我能想到的唯一替代方法是操纵正在使用的pandas格式化程序。但我不知道有什么连贯的方法可以做到这一点。matplotlib中的二次_y等效于创建一个
twinx
,并将第二个绘图绘制到该轴上。这通常会导致3个代码行与1个代码行相比,所以它没有那么糟糕。不确定问题是什么。这里最简单的方法是
fig.autofmt\u xdate(旋转=90)