Python 3.x 如何在使用where参数之间使用fill_

Python 3.x 如何在使用where参数之间使用fill_,python-3.x,matplotlib,Python 3.x,Matplotlib,因此,在一个教程之后,我尝试使用以下代码创建一个图形: 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, executi

因此,在一个教程之后,我尝试使用以下代码创建一个图形:

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线上方的区域,而下面的区域没有着色,所以我创建了一个名为threshold的列表,并将其填充为1,以便重新创建比较。但是,

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

创建完全相同的图形,即使执行时间值超过1

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

问题主要是由于使用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()

我现在做了一些编辑,使代码基本上可以运行。
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()