使用 matplotlib 绘制时间序列 Pandas 数据框时标签错误 [英] Wrong labels when plotting a time series pandas dataframe with matplotlib

查看:72
本文介绍了使用 matplotlib 绘制时间序列 Pandas 数据框时标签错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个包含 1 周数据的数据框.

I am working with a dataframe containing data of 1 week.

                          y
ds                             
2017-08-31 10:15:00    1.000000
2017-08-31 10:20:00    1.049107
2017-08-31 10:25:00    1.098214
...
2017-09-07 10:05:00   99.901786
2017-09-07 10:10:00   99.950893
2017-09-07 10:15:00  100.000000

我通过结合工作日和时间来创建一个新索引,即

I create a new index by combining the weekday and time i.e.

                y
dayIndex             
4 - 10:15    1.000000
4 - 10:20    1.049107
4 - 10:25    1.098214
...
4 - 10:05   99.901786
4 - 10:10   99.950893
4 - 10:15  100.000000

该数据的图如下:该图是正确的,因为标签反映了数据框中的数据.但是,放大时,标签看起来不正确,因为它们不再对应于其原始值:是什么导致了这种行为?

The plot of this data is the following: The plot is correct as the labels reflect the data in the dataframe. However, when zooming in, the labels do not seem correct as they no longer correspond to their original values: What is causing this behavior?

这是重现此内容的代码:

Here is the code to reproduce this:

import datetime
import numpy as np
import pandas as pd

dtnow = datetime.datetime.now()
dindex = pd.date_range(dtnow , dtnow  + datetime.timedelta(7), freq='5T')
data = np.linspace(1,100, num=len(dindex))
df = pd.DataFrame({'ds': dindex, 'y': data})
df = df.set_index('ds')
df = df.resample('5T').mean()
df['dayIndex'] = df.index.strftime('%w - %H:%M')
df= df.set_index('dayIndex')
df.plot()

推荐答案

是什么导致了这种行为?"

熊猫日期图的轴的格式化程序是 matplotlib.ticker.FixedFormatter (例如,参见打印 plt.gca().xaxis.get_major_formatter()).固定"表示它使用一些常量字符串格式化 i 滴答声(如果显示).

The formatter of an axes of a pandas dates plot is a matplotlib.ticker.FixedFormatter (see e.g. print plt.gca().xaxis.get_major_formatter()). "Fixed" means that it formats the ith tick (if shown) with some constant string.

缩放或平移时,移动刻度位置,但不移动格式字符串.
简而言之:大熊猫日期图可能不是交互式图的最佳选择.

When zooming or panning, you shift the tick locations, but not the format strings.
In short: A pandas date plot may not be the best choice for interactive plots.

解决方案

一个解决方案通常是直接使用 matplotlib 格式化程序.这要求日期是 datetime 对象(可以使用 df.index.to_pydatetime() 确保).

A solution is usually to use matplotlib formatters directly. This requires the dates to be datetime objects (which can be ensured using df.index.to_pydatetime()).

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

dtnow = datetime.datetime.now()
dindex = pd.date_range(dtnow , dtnow  + datetime.timedelta(7), freq='110T')
data = np.linspace(1,100, num=len(dindex))
df = pd.DataFrame({'ds': dindex, 'y': data})
df = df.set_index('ds')
df.index.to_pydatetime()
df.plot(marker="o")


plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%w - %H:%M'))
plt.show()

这篇关于使用 matplotlib 绘制时间序列 Pandas 数据框时标签错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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