python - ipython plotly : cannot plot x-axis as datetime

标签 python datetime matplotlib plotly

所以,我在 pandas 数据框中有数据,其中行名称在日期时间 pandas.tseries 中给出。我可以在 matplotlib 中绘制数据并得到这个数字:

enter image description here

但是,我想使用plotly 在 inetarctive 模式下绘制相同的图形。它的工作原理如下,但它不显示日期时间,而是用整数索引替换 x 轴!

https://plot.ly/~vmirjalily/5/

上面 URL 中的图是使用以下代码绘制的:

dfmean = df.mean(axis=1)
dfmean_mavg = pd.rolling_mean(dfmean, 50)

dfmean.plot(linewidth=1.5, label='Mean of 20')
dfmean_mavg.plot(linewidth=3, label='Moving Avg.')
#plt.legend(loc=2)

l1 = plt.plot(dfmean, 'b-', linewidth=3)
l2 = plt.plot(dfmean_mavg, 'g-', linewidth=4)

mpl_fig1 = plt.gcf()

py.iplot_mpl(mpl_fig1, filename='avg-price.20stocks')

但此代码不显示 x 轴中的日期时间索引。我尝试强制日期时间索引如下:

l1 = plt.plot(np.array(dfmean.index), dfmean, 'b-', linewidth=3)
l2 = plt.plot(np.array(dfmean_mavg.index), dfmean_mavg, 'g-', linewidth=4)

mpl_fig1 = plt.gcf()

py.iplot_mpl(mpl_fig1, filename='avg-price.20stocks')

但它给出了一长串错误,如下所示

:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-35-4a3ca217202d> in <module>()
     14 mpl_fig1 = plt.gcf()
     15 
---> 16 py.iplot_mpl(mpl_fig1, filename='avg-price.20stocks')

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in iplot_mpl(fig, resize, strip_style, update, **plot_options)
    257             "object. Run 'help(plotly.graph_objs.Figure)' for more info."
    258         )
--> 259     return iplot(fig, **plot_options)
    260 
    261 

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in iplot(figure_or_data, **plot_options)
    113     if 'auto_open' not in plot_options:
    114         plot_options['auto_open'] = False
--> 115     res = plot(figure_or_data, **plot_options)
    116     urlsplit = res.split('/')
    117     username, plot_id = urlsplit[-2][1:], urlsplit[-1]  # TODO: HACKY!

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in plot(figure_or_data, validate, **plot_options)
    212                 pass
    213     plot_options = _plot_option_logic(plot_options)
--> 214     res = _send_to_plotly(figure, **plot_options)
    215     if res['error'] == '':
    216         if plot_options['auto_open']:

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.pyc in _send_to_plotly(figure, **plot_options)
    971     fig = tools._replace_newline(figure)  # does not mutate figure
    972     data = json.dumps(fig['data'] if 'data' in fig else [],
--> 973                       cls=utils._plotlyJSONEncoder)
    974     username, api_key = _get_session_username_and_key()
    975     kwargs = json.dumps(dict(filename=plot_options['filename'],

/usr/lib/python2.7/json/__init__.pyc in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, **kw)
    236         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    237         separators=separators, encoding=encoding, default=default,
--> 238         **kw).encode(obj)
    239 
    240 

/usr/lib/python2.7/json/encoder.pyc in encode(self, o)
    199         # exceptions aren't as detailed.  The list call should be roughly
    200         # equivalent to the PySequence_Fast that ''.join() would do.
--> 201         chunks = self.iterencode(o, _one_shot=True)
    202         if not isinstance(chunks, (list, tuple)):
    203             chunks = list(chunks)

/usr/lib/python2.7/json/encoder.pyc in iterencode(self, o, _one_shot)
    262                 self.key_separator, self.item_separator, self.sort_keys,
    263                 self.skipkeys, _one_shot)
--> 264         return _iterencode(o, 0)
    265 
    266 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/usr/local/lib/python2.7/dist-packages/plotly/utils.pyc in default(self, obj)
    144                 if s is not None:
    145                     return s
--> 146             raise e
    147         return json.JSONEncoder.default(self, obj)
    148 

TypeError: masked is not JSON serializable

这是我的软件包版本:

IPython 2.0.0
numpy 1.9.0
numexpr 2.2.2
pandas 0.15.0
matplotlib 1.4.0
plotly 1.4.7

以及我的数据框的前 10 行:

Date
2011-01-04    54.2430
2011-01-05    54.3935
2011-01-06    54.4665
2011-01-07    54.5920
2011-01-10    54.9435
2011-01-11    54.9340
2011-01-12    55.4755
2011-01-13    55.5495
2011-01-14    56.0230
dtype: float64

最佳答案

这里发生了一些事情。

回溯:

此回溯告诉您无法序列化屏蔽数字。掩码数字与 NaN 略有不同。如果您好奇的话,这里有一些信息:http://pandas.pydata.org/pandas-docs/dev/gotchas.html#nan-integer-na-values-and-na-type-promotions

屏蔽数字的原因是您进行的移动平均计算。它会生成前 N 个值,其中 N 是您要平均、屏蔽的点数。

因此,如果您通过操作数据框来消除屏蔽值,您将不会再看到这个问题。

DataFrame.to_json() 对屏蔽值执行的操作中获取队列(将它们变为 null),在列表中替换的最合适的值是如果你尝试走那条路。 None 最好翻译为 null

x 轴上的整数

一些背景知识。当日期位于 matplotlib 中时,它们是浮点值,表示自 0001-01-01 + 1 以来的天数(有关详细信息,请参阅 matplotlib 日期)。但是,导入 pandas 会改变它以使用不同的日期表示形式,即自 UNIX 纪元以来的天数,另一个 float 。 plotly 中的版本 1.4.7 旨在通过转换回 ISO 字符串来处理这两个差异,但也许您发现了另一种途径。不过,我似乎无法重新创建此错误。这是我尝试过的代码:

import random
import pandas as pd
import matplotlib.pyplot as plt
import plotly.plotly as py
import plotly.tools as tls
num_pts = 1000
data = [random.random() for i in range(num_pts)]
index = pd.date_range('2011-01-04', periods=num_pts)
df = pd.DataFrame(data=data, index=index)
dfmean = df.mean(axis=1)
dfmean_mavg = pd.rolling_mean(dfmean, 50)
dfmean.plot(linewidth=1.5, label='Mean of 20')
# dfmean_mavg.plot(linewidth=3, label='Moving Avg.')

mpl_fig1 = plt.gcf()
py.plot_mpl(mpl_fig1, filename='avg-price.20stocks')

在系列上调用plt.plot

您似乎尝试将数据部分绘制两次?我更熟悉直接在数据帧上调用 plot 方法,这就是为什么我选择仅在上面的代码片段中包含此版本。

TL;DR,修复它即可。

Plotly 的 python api GH 存储库上有一个 PR 可以处理这个问题:https://github.com/plotly/python-api/pull/159 。明天应该会在 PyPi 上发布。

关于python - ipython plotly : cannot plot x-axis as datetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053729/

相关文章:

javascript - moment.utc(date).local() 仍然给出 utc 时间。

json - 如何停止 Pandas Dataframe read_json 方法将我的时代转换为人类可读的字符串

Python:如何查看 Unix 时间戳是在一天中的某个时间之前还是之后

python - 如何在 matplotlib 中为自定义图例添加阴影线?

Python Seaborn Facetgrid 改变 xlabels

python - 构建我的 Django 第三方应用程序的最佳方式是什么

python - pip 无法安装包 - Dockerfile

python - 属性错误: module 'socket' has no attribute 'MSG_DONTWAIT'

用于多选项卡绘图的 python matplotlib 和 PyQT - 导航

python - Pyspark RDD .filter() 带通配符