【2.8.3】图形填充fill/fill_between

一、绘制填充多边形fill()

1.1 语法结构

fill(*args, **kwargs)

args - sequence of x, y, [color]

ax.fill(x, y)                    # a polygon with default color
ax.fill(x, y, "b")               # a blue polygon
ax.fill(x, y, x2, y2)            # two polygons
ax.fill(x, y, "b", x2, y2, "r")  # a blue and a red polygon

kwargs - 对象matplotlib.patches.Polygon的特性(class:~matplotlib.patches.Polygon properties)

1.2 示例

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5 * np.pi, 1000)

y1 = np.sin(x)
y2 = np.sin(2 * x)

plt.plot(x, y1, label="$ y = sin(x) $")
plt.plot(x, y2, label="$ y = sin(2 * x) $")
plt.legend(loc=3)

plt.show()

绘制填充图

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5 * np.pi, 1000)

y1 = np.sin(x)
y2 = np.sin(2 * x)

plt.fill(x, y1, color="g", alpha=0.3)
plt.fill(x, y2, color="b", alpha=0.3)

plt.show()

二、函数间区域填充fill_between

2.1 基本语法

两函数间的Y轴方向的填充

plt.fill_between(
    x, y1, y2=0, where=None, 
    interpolate=False, step=None, 
    hold=None, data=None, 
    **kwargs
)


x - array( length N) 定义曲线的 x 坐标

y1 - array( length N ) or scalar 定义第一条曲线的 y 坐标

y2 - array( length N )  or scalar 定义第二条曲线的 y 坐标

where - array of bool (length N), optional, default: None 

             排除一些(垂直)区域被填充。

             注:我理解的垂直区域,但帮助文档上写的是horizontal regions

也可简单地描述为

plt.fill_between(x,y1,y2,where=条件表达式, color=颜色,alpha=透明度)

" where = " 可以省略,直接写条件表达式 

2.2 具体示例

通过调换 y1 和 y2 的顺序,图形的 “ 形貌 ” 不发生变化。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5 * np.pi, 1000)

y1 = np.sin(x)
y2 = np.sin(2 * x)

plt.plot(x, y1, c="g")
plt.plot(x, y2, c='r')

# 将两函数间区域填充成浅灰色
plt.fill_between(x, y1, y2, facecolor="lightgray")

plt.show()

将函数复杂化

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5 * np.pi, 1000)

y1 = np.sin(x)
y2 = np.sin(2 * x)

plt.plot(x, y1, c="y")
plt.plot(x, y2, c='r')

# 将两函数间区域填充成浅灰色
plt.fill_between(x, y1, y2, facecolor="lightgray")

plt.show()

我们看到,其实只要介于两函数值之间的区域均被 lightgray 颜色填充了。

进一步通过 where = 条件表达式 (这里的 where = 省略了 )该表图形 “ 形貌 ” 。

import numpy as np
import matplotlib.pyplot as plt
n = 1000
x = np.linspace(0, 8 * np.pi, n)
sin_y = np.sin(x)
cos_y = np.cos(x / 2) / 2

plt.figure('Fill', facecolor='lightgray')
plt.title('Fill', fontsize=20)
plt.xlabel('x', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.tick_params(labelsize=10)
plt.grid(linestyle=':')

# 把正弦余弦两条曲线画出
plt.plot(x, sin_y, c='dodgerblue', label=r'$y=sin(x)$')
plt.plot(x, cos_y, c='orangered',
        label=r'$\frac{1}{2}cos(\frac{x}{2})$')

# 填充
plt.fill_between(x, cos_y, sin_y, cos_y < sin_y,
                color='dodgerblue', alpha=0.5)
plt.fill_between(x, cos_y, sin_y, cos_y > sin_y,
                color='orangered', alpha=0.5)

plt.legend(loc = 3)
plt.show()

参考资料

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn