【发布时间】:2018-05-20 18:24:30
【问题描述】:
我有一个简单的数据集,我想将它显示在与在不同时间收集的重量相对应的条形图中。我希望它与我之前估计的误差条累积。由于权重对应于一定时间段内的累积,所以我希望条形为它所代表的时间的宽度。
入口文件格式为:
Date Weight Deviation
2017-05-04 500 100
2017-05-08 7.4 0.3
2017-05-13 6.4 0.3
2017-05-21 8.7 0.27
2017-06-06 16.8 0.7
2017-06-07 14.4 0.6
2017-06-18 13.7 0.6
2017-06-25 16.3 0.7
2017-07-02 17 0
2017-07-09 17 0
2017-07-26 20 0
2017-08-11 19 0
2017-08-23 12 0
2017-09-03 27 0
2017-09-11 15 0
2017-09-16 60 0
代码如下:
import os, sys, datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
DATA = np.genfromtxt(Path_to_File, dtype=[('Date','datetime64[D]'),('Weight', 'float32'), ('Deviation', 'float32')], delimiter ='\t', skip_header = 1)
Days = np.zeros(len(DATA)-1, dtype = 'datetime64[D]')
Duration = np.zeros(len(DATA)-1, dtype = 'timedelta64[D]')
for i in range(1, len(DATA)):
DayOut = DATA[i][0]
DayIn = DATA[i-1][0]
Duration[i-1] = DayOut - DayIn
Days[i-1] = DayIn + Duration[i-1]/2
fig2 = plt.figure()
ax = fig2.add_subplot(111)
fig2.suptitle('FigureTitle', fontsize=16)
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.bar(Days, DATA['Weight'].cumsum()[1:], width=Duration, yerr = DATA['Deviation'][1:])
ax.set_ylabel('Cumulative weight (kg)')
ax.set_xlabel('Date')
plt.show()
我收到此错误消息
Cannot cast ufunc less input from dtype('<m8[D]') to dtype('<m8') with casting rule 'same_kind'
这很棘手,因为我认为它会在日期(datetime64)、Days 数组和宽度的持续时间(timedelta64)、Duration 数组之间感到恼火。 我有点卡住了,我想我必须只做一个持续时间轴?有什么经验或建议吗? 提前致谢
【问题讨论】:
-
恐怕这是不可能的,因为 matplotlib 现在是如何工作的。它将日期时间转换为数字以生成 x 轴。一种解决方法是使用自开始以来的天数作为 x 轴,然后手动添加刻度。
ax.bar((Days-min(Days)).astype(int), DATA['Weight'].cumsum()[1:], width=Duration.astype(int), yerr = DATA['Deviation'][1:]) -
@HaochenWu 我不知道这里应该有什么不可能,但是根据日历手动设置标签可能不是一个好主意。
标签: python date numpy datetime matplotlib