【问题标题】:Shade area between 2 y coordinates in matplotlibmatplotlib中2 y坐标之间的阴影区域
【发布时间】:2018-06-01 15:15:42
【问题描述】:

我正在尝试基于两个垂直坐标创建一个阴影矩形(矩形的长度应该跨越整个 x 轴)。 我尝试将fill_between 与以下内容一起使用(p1 和 p2 是数据坐标):

f, ax1 = plt.subplots()   
x = np.linspace(200,300,2000)
y = x**(2)
y1 = x
p1 = 4700
p2 = 7700

ax1.plot(x, y, lw=2)
ax1.set_xlabel('Temperature $[K]$', fontweight='bold')
ax1.set_ylabel('Pressure $[mb]$', fontweight='bold')
ax1.fill_between(x, y1.fill(p1), y1.fill(p2))

但我收到以下错误:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

怎么了?有更好的方法吗?

谢谢!!

【问题讨论】:

  • y1.fill(p1) 不返回数组!

标签: python matplotlib


【解决方案1】:

可能你的意思是使用axhspan

p1 = 4700
p2 = 7700
ax1.axhspan(p1, p2, color="limegreen", alpha=0.5)

【讨论】:

  • 谢谢!但是我可以让阴影区域更透明并使用另一种颜色吗?
【解决方案2】:

IIUC,问题在于.fill() 函数的使用。您可以避免这种情况,将fill_betweenx 数组一起使用,并且只使用p1p2 值,因为fill_between 可以接受y1y2 的标量值。

ax1.fill_between(x, p1, p2)

注意,您可以通过添加 coloralpha 参数轻松更改颜色和透明度:

ax1.fill_between(x, p1, p2, color='limegreen', alpha=0.5)

【讨论】:

    【解决方案3】:

    数组的fill 方法不返回数组,它返回None

    【讨论】:

      【解决方案4】:

      你误解了fill_between。使用时建议将y 表示为函数:

      def y(x):
          return x**2
      section = np.arange(start,end,0.1)
      plt.fill_between(section,y(section))
      

      将为startend 提供合适的值。

      【讨论】:

      • OP中fill_between的使用方式是正确的,但是y1.fill(p1)None,不是数组。
      • 错了。我就是这样使用它的——它有效。
      • 这个答案本身是正确的,但不能满足问题的要求,因为它填充了 y=0 和 y=x**2 定义的行之间的区域。它不会产生一个矩形。
      • 是的,对数组应用函数的结果是数组,因此您使用 fill_between 的方式有效,但这并没有指出 OP 中的问题。
      • 这个答案似乎很盲目地从here复制而来。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多