使用 pandas 时无法设置日期时间刻度 [英] Cannot set datetime ticks when using pandas

查看:43
本文介绍了使用 pandas 时无法设置日期时间刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图用熊猫绘制一些系列.但是,当我尝试在日期轴上设置主要定位符时,我遇到了问题.

如果您想尝试使用与我相同的数据集,

我的 DataFrame 看起来像这样:

数据集1数据集22018-04-16 00:00:00 0.000000 0.5166672018-04-16 00:15:00 0.011111 0.2444442018-04-16 00:30:00 0.000000 0.3888892018-04-16 00:45:00 0.000000 0.2111112018-04-16 01:00:00 0.000000 0.127778……2018-04-19 22:45:00 0.022222 0.2500002018-04-19 23:00:00 0.166667 0.5055562018-04-19 23:15:00 0.000000 0.6888892018-04-19 23:30:00 0.000000 1.7333332018-04-19 23:45:00 0.055556 0.283333[384 行 x 2 列]

解决方案

如果您想在 Pandas 生成的绘图上使用 matplotlib.dates 定位器和格式化程序,则需要以兼容性方式绘图模式,

  df.plot(...,x_compat = True)

I am trying to plot some series with pandas. However I have a problem when I try to set major locator on axis with dates.

If you want to try on the same dataset as mine, here's the pickle.

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

df = pd.read_pickle('df.pkl')
df = df.set_index('time')

ax = df.plot(y=['dataset1', 'dataset2'], figsize=(10,5))

h_locator = mdates.HourLocator(byhour=[0, 6, 12, 18])
ax.xaxis.set_major_locator(h_locator)
ax.grid(True)
plt.show()

I want to display 4 grid ticks per day (hours: 0, 6, 12 and 18) but the output is the same as if I would not set any locator.

My DataFrame looks like this:

                     dataset1  dataset2
2018-04-16 00:00:00  0.000000  0.516667
2018-04-16 00:15:00  0.011111  0.244444
2018-04-16 00:30:00  0.000000  0.388889
2018-04-16 00:45:00  0.000000  0.211111
2018-04-16 01:00:00  0.000000  0.127778
                       ...       ...
2018-04-19 22:45:00  0.022222  0.250000
2018-04-19 23:00:00  0.166667  0.505556
2018-04-19 23:15:00  0.000000  0.688889
2018-04-19 23:30:00  0.000000  1.733333
2018-04-19 23:45:00  0.055556  0.283333
[384 rows x 2 columns]

解决方案

In case you want to use the matplotlib.dates locators and formatters on a plot generated by pandas, you need to plot in compatibility mode,

df.plot(..., x_compat=True)

这篇关于使用 pandas 时无法设置日期时间刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆