Matplotlib的fill_between不适用于plot_date,还有其他选择吗? [英] Matplotlib's fill_between doesnt work with plot_date, any alternatives?

查看:106
本文介绍了Matplotlib的fill_between不适用于plot_date,还有其他选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样创建一个图:

I want to create a plot just like this:

代码:

P.fill_between(DF.start.index, DF.lwr, DF.upr, facecolor='blue',   alpha=.2)
P.plot(DF.start.index, DF.Rt, '.')

,但在x轴上带有日期,如下所示(不带):

but with dates in the x axis, like this (without bands):

代码:

P.plot_date(DF.start, DF.Rt, '.')

问题是当x值是date_time对象时,fill_between失败.

the problem is that fill_between fails when x values are date_time objects.

有人知道解决方法吗? DF是一个熊猫DataFrame.

Does anyone know of a workaround? DF is a pandas DataFrame.

推荐答案

如果您显示df的定义,将会很有帮助. df.info()报告什么?这将向我们显示列的dtypes.

It would help if you show how df is defined. What does df.info() report? This will show us the dtypes of the columns.

日期有多种表示方式:字符串,整数,浮点数,datetime.datetime,NumPy datetime64s,Pandas时间戳或Pandas DatetimeIndex.绘制它的正确方法取决于您所拥有的.

There are many ways that dates can be represented: as strings, ints, floats, datetime.datetime, NumPy datetime64s, Pandas Timestamps, or Pandas DatetimeIndex. The correct way to plot it depends on what you have.

下面是一个示例,显示了如果df.index是DatetimeIndex:

Here is an example showing your code works if df.index is a DatetimeIndex:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

index = pd.date_range(start='2000-1-1', end='2015-1-1', freq='M')
N = len(index)
poisson = (stats.poisson.rvs(1000, size=(N,3))/100.0)
poisson.sort(axis=1)
df = pd.DataFrame(poisson, columns=['lwr', 'Rt', 'upr'], index=index)

plt.fill_between(df.index, df.lwr, df.upr, facecolor='blue', alpha=.2)
plt.plot(df.index, df.Rt, '.')
plt.show()

如果索引具有日期的字符串表示形式,则(对于Matplotlib版本1.4.2),您将收到TypeError:

If the index has string representations of dates, then (with Matplotlib version 1.4.2) you would get a TypeError:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

index = pd.date_range(start='2000-1-1', end='2015-1-1', freq='M')
N = len(index)
poisson = (stats.poisson.rvs(1000, size=(N,3))/100.0)
poisson.sort(axis=1)
df = pd.DataFrame(poisson, columns=['lwr', 'Rt', 'upr'])

index = [item.strftime('%Y-%m-%d') for item in index]
plt.fill_between(index, df.lwr, df.upr, facecolor='blue', alpha=.2)
plt.plot(index, df.Rt, '.')
plt.show()

收益

  File "/home/unutbu/.virtualenvs/dev/local/lib/python2.7/site-packages/numpy/ma/core.py", line 2237, in masked_invalid
    condition = ~(np.isfinite(a))
TypeError: Not implemented for this type

在这种情况下,解决方法是将字符串转换为时间戳:

In this case, the fix is to convert the strings to Timestamps:

index = pd.to_datetime(index)

这篇关于Matplotlib的fill_between不适用于plot_date,还有其他选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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