我有两个时间序列值和两条垂直线,下面的线图,我想给“FromGen”大于“ToCons”的区域和两条垂直线的外侧涂上颜色
start_date="2019-06-18"
end_date="2019-06-19"
x0='2019-06-18 9:00:00'
x1='2019-06-18 17:00:00'
x1= pd.to_datetime(x1, format="%Y-%m-%d", utc=True)
x2= pd.to_datetime(x2, format="%Y-%m-%d", utc=True)
zeit = (df['DateTime'] > start_date) & (df['DateTime'] <= end_date)
zeit = df.loc[zeit]
zeit.plot(figsize=(15,10),x="DateTime", y=["FromGen", "ToCons"])
plt.xlabel("Zeit")
plt.ylabel("Wh")
legend = plt.legend(title="comp",
loc=1, fontsize='large', fancybox=True, labels=['FromGen', 'ToCons'])
plt.axvline(x=x0, color='red')
plt.axvline(x=x1, color='red')
kde_x, kde_y = ax.lines[0].get_data()
ax.fill_between(kde_x, kde_y, where=(kde_x<x0) | (kde_x>x1) ,
interpolate=True, color='#8FF536')
plt.show()
我已经发现最后几行中的代码可能会有所帮助,但目前我正纠结于这个错误:
'<' not supported between instances of 'numpy.ndarray' and 'str'
非常感谢
编辑: 这就是我的代码目前的样子——如果我不将df转换为正确的tz,那么一切都会很完美。但当我这样做的时候,绿色区域会被移动。我想我错过了一个时区转换的地方,但找不到在哪里
从日期时间导入日期时间 从pytz导入时区
df=pd.read_csv(“filename.csv”,error_bad_lines=False,sep=“;”) df['DateTime']=pd.to_DateTime(df['DateTime'],format=“%Y-%m-%d”,utc=True)
#df['DateTime']=df['DateTime'].dt.tz_convert('欧洲/柏林') #没有这条线效果很好!但当我使用它时,彩色区域似乎位于错误的时区
start_date = "2019-06-18" end_date = "2019-06-19"
x0 = '2019-06-18 9:00:00' x1 = '2019-06-18 16:00:00'
zeit = df.loc[(df['DateTime'] > start_date) & (df['DateTime'] <= end_date)]
ax = zeit.plot(figsize=(15, 10), x="DateTime", y=["FromGen", "ToCons"])
ax.set_xlabel("Zeit") ax.set_ylabel("Wh") legend = ax.legend(title="comp",
loc='upper right', fontsize='large', fancybox=True, labels=['FromGen', 'ToCons']) ax.axvline(x=x0, color='red') ax.axvline(x=x1, color='red')
x0 = datetime_obj.replace(tzinfo=timezone('UTC'))
ax.fill_between(zeit['DateTime'].values, zeit['FromGen'], zeit['ToCons'],
where=((zeit['FromGen'] > zeit['ToCons']) & ((zeit['DateTime'] <= x0) | (zeit['DateTime'] >=x1))),
interpolate=False, color='#8FF536') plt.show()
在最近的pandas和matplotlib版本中,处理日期已经有了很大的发展。因此,引用旧帖子可能会产生误导。以下代码已使用matplotlib 3.4.1和pandas 1.2.4进行了测试
问题代码中有一点奇怪,即首先使用
x0
和x1
,然后使用x1
和x2
而不给x2
赋值plt.fill_between()
可以直接使用数字列。要使用datatime列,现在它可以使用...['DateTime'].values
。对于where
子句,要比较datetime列,需要使用pd.to_datetime(...)
转换x0和x1。由于我的示例中的datetime值没有utc
,因此使用x0 = pd.to_datetime(..., utc=True)
时比较不起作用还请注意,pandas plotting(
zeit.plot(...)
)返回matplotlibax
相关问题 更多 >
编程相关推荐