如何将 axvfill 与布尔系列一起使用 [英] How do I use axvfill with a boolean series

查看:25
本文介绍了如何将 axvfill 与布尔系列一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布尔时间序列,我想用它来确定应该着色的绘图部分.

I have a boolean time series that I want to use to determine the parts of the plot that should be shaded.

目前我有:

ax1.fill_between(data.index, r_min, r_max, where=data['USREC']==True, alpha=0.2)

其中,r_minr_max 只是 y 轴的最小值和最大值.

where, r_min and r_max are just the min and max of the y-axis.

但是 fill_between 并没有一直填充到图的顶部和底部,因为,所以我想使用 axvspan() 代替.

But the fill_between doesn't fill all the way to the top and bottom of the plot because, so I wanted to use axvspan() instead.

有没有什么简单的方法可以做到这一点,因为 axvspan 只需要坐标?所以我能想到的唯一方法是将所有相邻且为 True 的日期分组,然后将这些日期中的第一个和最后一个日期传递给 axvspan.

Is there any easy way to do this given axvspan only takes coordinates? So the only way I can think of is to group all the dates that are next to each other and are True, then take the first and last of those dates and pass them into axvspan.

谢谢

推荐答案

如果愿意,您仍然可以使用 fill_between .但是,您可以在坐标轴中指定它们,而不是在数据坐标中指定 y 坐标(对于这点尚不清楚,它们需要多大).这可以使用变换来实现,其中 x 部分在数据坐标中,y 部分在轴坐标中.xaxis变换就是这样的变换.(这并不奇怪,因为x轴始终独立于ycoorinates.)因此

You can still use fill_between, if you like. However instead of specifying the y-coordinates in data coordinates (for which it is not a priori clear, how large they need to be) you can specify them in axes coorinates. This can be achieved using a transform, where the x part is in data coordinates and the y part is in axes coordinates. The xaxis transform is such a transform. (This is not very surprising since the xaxis is always independent of the ycoorinates.) So

ax.fill_between(data.index, 0,1, where=data['USREC'], transform=ax.get_xaxis_transform())

会做这项工作.

这是一个完整的示例:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,100,350)
y = np.cumsum(np.random.normal(size=len(x))) 
bo = np.zeros(len(y))
bo[y>5] = 1

fig, ax = plt.subplots()
ax.fill_between(x, 0, 1, where=bo, alpha=0.4, transform=ax.get_xaxis_transform())

plt.plot(x,y)
plt.show()

这篇关于如何将 axvfill 与布尔系列一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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