实例:绘制积分图

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpat

# 平均取-4,4之间的数,默认50个
x = np.linspace(-4, 4)

# 指定函数
y = np.tanh(x)

# 添加画布
fig = plt.figure()

# 绘制坐标系
ax = fig.add_subplot(111)

# 在此坐标系绘图
ax.plot(x, y)

# 设置坐标系居中
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

# 绘制渐近线
y1 = [1 for y1 in x]
l1, = ax.plot(x, y1, color='r')

y2 = [-1 for y1 in x]
l2, = ax.plot(x, y2, color='r')

# 渐近线样式
l1.set_linestyle('--')
l2.set_linestyle('--')

# 积分取值范围
a = -3
b = 3

# 设置坐标轴刻度
ax.set_xticks([a, b])
ax.set_yticks([])

# 设置坐标轴刻度显示
ax.set_xticklabels(['$a$', '$b$'])

# 添加label
fig.text(0.5, 0.95, "$y$")
fig.text(0.95, 0.42, "$x$")

# 隐藏图边框
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')

# 积分取值范围的x坐标
ix = np.linspace(-3, 3)

# 积分取值y坐标
iy = np.tanh(ix)

# 集合积分图形坐标
xy = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]

# 绘制(多边形)积分图形
patch = mpat.Polygon(xy, facecolor='0.9', edgecolor='0.5')

# 添加多边形
ax.add_patch(patch)

# 
plt.xlim(right=5)
plt.ylim(top=1.2)

# 添加坐标轴箭头
ax.arrow(5, 0, -0.1, -0.05)
ax.arrow(5, 0, -0.1, 0.05)
ax.arrow(0, 1.2, -0.1, -0.05)
ax.arrow(0, 1.2, 0.1, -0.05)

# 添加公式
ax.text(a, 0.54, r"$ \int_a^b tanh(x)dx $", size=20)

plt.show()

在这里插入图片描述

发布了45 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_22096121/article/details/103571841