pandas 如何每小时获得一次滴答声?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48790378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:10:50  来源:igfitidea点击:

how to get ticks every hour?

pythonpandasmatplotlib

提问by ??????

Consider this simple example

考虑这个简单的例子

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

I want to plot this, and have ticks every hour. I use:

我想绘制这个图,并且每小时都有一个滴答声。我用:

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)

which gives

这使

enter image description here

在此处输入图片说明

why dont the ticks appear every hour here? Thanks for your help!

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

回答by ImportanceOfBeingErnest

The problem is that while pandas in general directly wraps the matplotlib plotting methods, this is not the case for plots with dates. As soon as dates are involved, pandas uses a totally different numerical representation of dates and hence also uses its own locators for the ticks.

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

In case you want to use matplotlib.datesformatters or locators on plots created with pandas you may use the x_compat=Trueoption in pandas plots.

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

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

This allows to use the matplotlib.datesformatters or locators as shown below. Else you may replace df.plot(ax = ax, color = 'black', linewidth = 0.4)by

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

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

Complete example:

完整示例:

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_ysecondary_y,则 matplotlib 绘图的等效项将是双轴twinxtwinx

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

在此处输入图片说明