Matplotlib:fill, fill

您所在的位置:网站首页 农村柴火灶设计视频讲解 Matplotlib:fill, fill

Matplotlib:fill, fill

2023-12-03 05:30| 来源: 网络整理| 查看: 265

区域填充函数有 fill(*args, **kwargs)和fill_between()

1 绘制填充多边形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()

在这里插入图片描述

2 函数间区域填充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 具体示例 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()

在这里插入图片描述

我们看到,其实只要介于两函数值之间的区域均被 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='orangered', alpha=0.5) plt.legend(loc = 3) plt.show()

在这里插入图片描述

指定区间填充

# 填充 plt.fill_between(x, cos_y, sin_y, where=(cos_y


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3