填充线条之间的区域

此示例显示如何使用fill_between方法基于用户定义的逻辑在行之间着色。

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. x = np.arange(0.0, 2, 0.01)
  4. y1 = np.sin(2 * np.pi * x)
  5. y2 = 1.2 * np.sin(4 * np.pi * x)
  1. fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)
  2. ax1.fill_between(x, 0, y1)
  3. ax1.set_ylabel('between y1 and 0')
  4. ax2.fill_between(x, y1, 1)
  5. ax2.set_ylabel('between y1 and 1')
  6. ax3.fill_between(x, y1, y2)
  7. ax3.set_ylabel('between y1 and y2')
  8. ax3.set_xlabel('x')

填充线条之间的区域1

现在在满足逻辑条件的y1和y2之间填充。 请注意,这与调用fill_between(x[where], y1[where], y2[where]…)不同,因为多个连续区域的边缘效应。

  1. fig, (ax, ax1) = plt.subplots(2, 1, sharex=True)
  2. ax.plot(x, y1, x, y2, color='black')
  3. ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True)
  4. ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True)
  5. ax.set_title('fill between where')
  6. # Test support for masked arrays.
  7. y2 = np.ma.masked_greater(y2, 1.0)
  8. ax1.plot(x, y1, x, y2, color='black')
  9. ax1.fill_between(x, y1, y2, where=y2 >= y1,
  10. facecolor='green', interpolate=True)
  11. ax1.fill_between(x, y1, y2, where=y2 <= y1,
  12. facecolor='red', interpolate=True)
  13. ax1.set_title('Now regions with y2>1 are masked')

填充线条之间的区域2

这个例子说明了一个问题; 由于数据网格化,在交叉点处存在不期望的未填充三角形。 蛮力解决方案是在绘图之前将所有阵列插值到非常精细的网格。

使用变换创建满足特定条件的轴跨度:

  1. fig, ax = plt.subplots()
  2. y = np.sin(4 * np.pi * x)
  3. ax.plot(x, y, color='black')
  4. # use data coordinates for the x-axis and the axes coordinates for the y-axis
  5. import matplotlib.transforms as mtransforms
  6. trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
  7. theta = 0.9
  8. ax.axhline(theta, color='green', lw=2, alpha=0.5)
  9. ax.axhline(-theta, color='red', lw=2, alpha=0.5)
  10. ax.fill_between(x, 0, 1, where=y > theta,
  11. facecolor='green', alpha=0.5, transform=trans)
  12. ax.fill_between(x, 0, 1, where=y < -theta,
  13. facecolor='red', alpha=0.5, transform=trans)
  14. plt.show()

填充线条之间的区域3

下载这个示例