python - 如何在python中的3行之间使用fill_between
问题描述
我有一个包含我的 limit_up 值的列表,一个包含 limit_down 值的列表,以及一个填充了“100”值的第三个列表(其他列表的大小相同)。我想将limit_up和100之间的区域设置为绿色,将(100或limit_up)和limit_down之间的区域设置为红色',如下图所示。
但是,有时,由于我的 limit_down 列表没有任何低于 100 的值,因此该区域需要完全绿色。当我所有的 limit_up 值都低于 100 时,也会发生同样的情况,该区域需要全红。有人可以帮忙吗?
左图数据:
limit_down = ['8.5', '37.5', '45.2', '51.9', '55.0', '55.2', '56.7']
limit_up = ['982.6', '393.3', '286.2', '260.4', '232.9', '200.0', '201.7']
reference = [100 100 100 100 100 100 100]
右图数据:
limit_down = ['265.0', '649.1', '804.0', '895.1', '874.2', '957.9', '976.4']
limit_up = ['23815.5', '9043.4', '6932.4', '5805.6', '4510.5', '4317.5', '3963.5']
reference = [100 100 100 100 100 100 100]
解决方案
fill_between
和 numpy 的数组过滤可以如下使用来创建这些图:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 35, 7)
limit_down_1 = np.array([8.5, 37.5, 45.2, 51.9, 55.0, 55.2, 56.7])
limit_up_1 = np.array([982.6, 393.3, 286.2, 260.4, 232.9, 200.0, 201.7])
reference = 100
limit_down_2 = np.array([265.0, 649.1, 804.0, 895.1, 874.2, 957.9, 976.4])
limit_up_2 = np.array([23815.5, 9043.4, 6932.4, 5805.6, 4510.5, 4317.5, 3963.5])
fig, axes = plt.subplots(ncols=2, figsize=(12, 4))
for ax, limit_up, limit_down in zip(axes, [limit_up_1, limit_up_2], [limit_down_1, limit_down_2]):
ax.fill_between(x, np.maximum(reference, limit_down), limit_up, color='limegreen', alpha=0.3,
where=limit_up > reference, interpolate=True)
ax.fill_between(x, limit_down, np.minimum(reference, limit_up), color='crimson', alpha=0.3,
where=limit_down < reference, interpolate=True)
for y in (limit_up, limit_down):
ax.plot(x[y <= reference], y[y <= reference], color='crimson')
ax.plot(x[y >= reference], y[y >= reference], color='limegreen')
plt.show()
推荐阅读
- java - Android Studios:点击按钮解锁屏幕方向
- visual-studio - 如何在 Visual Studio 中更改程序图标?
- php - 尝试从作曲家安装 laravel 时缺少 PHP 扩展 zip
- python - 无法返回 [0,0] 和的空数组
- javascript - Moment isSameOrAfter 计算不正确
- angularjs - 服务器获取 `/customer/:id` 而不是实际的 id
- python - 无法在python中将xml文件转换为csv
- c# - API中POST上的模型绑定问题
- java - 什么是从具有至少 40 个文本字段的 fxml 的文本字段中获取 fx:id 的好方法
- php - 使用 php 上传 .docx 文件