【问题标题】:Matplotlib fill between method and datetimeMatplotlib 在方法和日期时间之间填充
【发布时间】:2017-06-04 21:46:47
【问题描述】:

我正在尝试使用 matplotlib fill_between 函数,但我收到以下错误“TypeError: ufunc 'isfinite' not supported for the input types, and the input can not be safe to becovered to any supported types based on cast rule ''安全''"

我在我的 x 轴中使用 pandas 日期时间,并认为这会引发这样的问题。我还没有找到解决办法。

这里是代码

#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Open file
f = open('rmm.74toRealtime.txt', 'r')

# Read and ignore header lines
header1 = f.readline()
header2 = f.readline()

n=15461-2
year=np.zeros(n)
month=np.zeros(n)
day=np.zeros(n)
rmm1=np.zeros(n)
rmm2=np.zeros(n)
phase=np.zeros(n)
ampl=np.zeros(n)
a=np.zeros(n)
b=np.zeros(n)

i=0
# Loop over lines and extract variables of interest
for line in f:
    line = line.strip()
    columns = line.split()
    year[i] = columns[0]
    month[i]=columns[1]
    day[i]=columns[2]
    rmm1[i]=columns[3]
    rmm2[i]=columns[4]
    phase[i]=columns[5]
    ampl[i]=columns[6]
    print([float(year[i]),float(month[i]),float(day[i]),float(rmm1[i]),float(rmm2[i]),float(phase[i]),float(ampl[i])])
    a[i]=str(int(year[i]))+str(int(month[i])).zfill(2) +str(int(day[i])).zfill(2) ;
    i=i+1
f.close()

w=pd.to_datetime(pd.Series(a),format='%Y%m%d')
yt=np.array(np.where((month == 1) & (day ==1)))
a=np.reshape(yt,len(yt[0,:]))

#%%
plt.close('all')
for i in a[:1]:   
    plt.figure()
    plt.plot(w[i:i+365],ampl[i:i+365])
    plt.fill_between(w[i:i+365],ampl[i:i+365],1)
    plt.title('RMM '+str(int(year[i])))
    plt.grid()
    plt.show()

这是数据文件的链接 ascii_file

谢谢

【问题讨论】:

标签: python python-2.7 python-3.x matplotlib ipython


【解决方案1】:

可以在this answer 中找到此问题的解决方案。因此,尝试

plt.fill_between(w.values[i:i+365],ampl[i:i+365],1)

【讨论】:

  • 非常感谢,很抱歉我的回复晚了,我正在旅行。
【解决方案2】:

此解决方法应该适用于 plt 和轴 plt.fill_between( w.dt.to_pydatetime(), data['A'],...。它将numpy datetime64[ns] 转换为fill_between 可以理解的python 日期时间。

顺便说一句,可以使用 pd.read_fwf 而不是 for loop 来读取修复格式。这是另一种懒惰的方式,但比循环快得多:

df = pd.read_csv(your_data_url,skiprows=2, header=None, sep="\n") df = df[0].str.split("\s+",expand=True).loc[:,1:7] df.columns = ['year','month','day','RMM1', 'RMM2', 'phase', 'amplitude']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多