首页 > 解决方案 > 如何利用 where 参数使用 fill_between

问题描述

因此,按照教程,我尝试使用以下代码创建图表:

time_values = [i for i in range(1,100)]
execution_time = [random.randint(0,100) for i in range(1,100)]
fig = plt.figure()
ax1 = plt.subplot()
threshold=[.8 for i in range(len(execution_time))]
ax1.plot(time_values, execution_time)
ax1.margins(x=-.49, y=0)
ax1.fill_between(time_values,execution_time, 1,where=(execution_time>1), color='r', alpha=.3)

这不起作用,因为我收到一个错误,说我无法比较列表和 int。但是,我随后尝试:

ax1.fill_between(time_values,execution_time, 1)

这给了我一个图表,其中执行时间和 y=1 线之间的所有区域都被填充了。因为我想要填充 y=1 线上方的区域,左下方的区域没有阴影,我创建了一个列表称为阈值,并用 1 填充它,以便我可以重新创建比较。然而,

ax1.fill_between(time_values,execution_time, 1,where=(execution_time>threshold)

ax1.fill_between(time_values,execution_time, 1)

创建完全相同的图表,即使执行时间值确实超过 1。

我很困惑有两个原因:首先,在我正在看的教程中,老师能够在fill_between函数中成功地比较一个列表和一个整数,为什么我不能做到这一点?其次,为什么 where 参数不能识别我要填充的区域?即,为什么图形在 y=1 和执行时间值之间的区域有阴影?

标签: python-3.xmatplotlib

解决方案


问题主要是由于使用了 python 列表而不是 numpy 数组。显然你可以使用列表,但是你需要在整个代码中使用它们。

import numpy as np
import matplotlib.pyplot as plt

time_values = list(range(1,100))
execution_time = [np.random.randint(0,100) for _ in range(len(time_values))]
threshold = 50


fig, ax = plt.subplots()

ax.plot(time_values, execution_time)
ax.fill_between(time_values, execution_time, threshold,
                where= [e > threshold for e in execution_time], 
                color='r', alpha=.3)

ax.set_ylim(0,None)
plt.show()

更好的是始终使用 numpy 数组。它不仅速度更快,而且更易于编码和理解。

import numpy as np
import matplotlib.pyplot as plt

time_values = np.arange(1,100)
execution_time = np.random.randint(0,100, size=len(time_values))
threshold = 50


fig, ax = plt.subplots()

ax.plot(time_values, execution_time)
ax.fill_between(time_values,execution_time, threshold,
                where=(execution_time > threshold), color='r', alpha=.3)

ax.set_ylim(0,None)
plt.show()

推荐阅读