【发布时间】:2021-03-04 10:56:40
【问题描述】:
我正在尝试使用matplotlib 绘制时间序列参数的观察值和计算值。观察到的数据存储在一个 XL 文件中,我使用openpyxl 读取该文件并转换为pandas dataframe。模拟值被读取为经过的天数,我将其转换为 numpy datetime 使用
delt = get_simulated_time()
t0 = np.datetime64('2004-01-01T00:00:00')
tsim = t0 + np.asarray(delt).astype('timedelta64[D]')
我使用以下代码 sn-p 绘制数据
df = obs_data_df.query("block=='blk-7'")
pobs = df['pres']
tobs = df['date']
tobs = np.array(tobs, dtype='datetime64')
print(type(tobs), np.min(tobs), np.max(tobs))
axs.plot(tobs, pobs, '.', color='g', label='blk-7, obs', markersize=8)
tsim = np.array(curr_sim_obj.tsim, dtype='datetime64')
print(type(tsim), np.min(tsim), np.max(tsim))
axs.plot(tsim, curr_sim_obj.psim[:, 0], '-', color='g', label='blk-7, sim', linewidth=1)
打印语句的结果是:
print(type(tobs), np.min(tobs), np.max(tobs))
... <class 'numpy.ndarray'> 2004-06-01T00:00:00.000000000 2020-06-01T00:00:00.000000000
print(type(tsim), np.min(tsim), np.max(tsim))
... <class 'numpy.ndarray'> 2004-01-01T00:00:00 2020-07-20T00:00:00
这些类型看起来不错,但我从 matplotlib 收到以下错误消息:
ValueError: view limit minimum -36907.706903627106 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
我不明白为什么我会收到此消息,因为打印语句表明数据是一致的。我尝试使用
print(np.dtype(tsim), np.min(tobs), np.max(tobs))
但收到此错误消息:
TypeError: data type not understood
这让我更加困惑,因为我在前面的语句中设置了tobs 数据类型。我不得不说,我对 python、pandas 和 numpy 处理日期的方式的差异以及上面的各种代码 kludges 反映了我在此过程中获得的解决方法感到非常困惑。我基本上想知道如何在同一个图上绘制两个不同的时间序列,所以非常欢迎所有建议。提前谢谢!
更新:
在削减代码以获得重现错误的更简单案例时,我发现以下代码隐藏在绘图例程中:
axs.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
这是从测试情节例程中遗留下来的。一旦我删除它,错误就消失了。我想我需要更仔细地检查我的代码...
【问题讨论】:
-
如果您想知道反对票,您的示例无法重现。如果日期在熊猫数据框中,为什么不将其转换为日期时间对象? pandas csv 阅读器甚至支持这一点,但要小心隐含的日期格式假设。关于 matplotlib 的日期时间格式的更多信息可以在这里找到:matplotlib.org/stable/api/dates_api.html
-
嗨,T 先生 - 想知道为什么这个问题被否决了......你使用 matplotlib 日期例程的建议解决了这个问题 - 我使用了 num2date 函数,事情按预期绘制。谢谢!
-
很高兴这个问题解决了。
-
这样的错误是人们被要求提供最少示例的原因。通常你自己找到解决方案;-)
标签: python pandas numpy matplotlib