积分作为曲线下面积

虽然这是一个简单的例子,但它展示了一些重要的调整:

  • 带有自定义颜色和线宽的简单线条图。
  • 使用Polygon补丁创建的阴影区域。
  • 带有mathtext渲染的文本标签。
  • figtext调用标记x轴和y轴。
  • 使用轴刺来隐藏顶部和右侧脊柱。
  • 自定义刻度线和标签。

积分作为曲线下面积

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.patches import Polygon
  4. def func(x):
  5. return (x - 3) * (x - 5) * (x - 7) + 85
  6. a, b = 2, 9 # integral limits
  7. x = np.linspace(0, 10)
  8. y = func(x)
  9. fig, ax = plt.subplots()
  10. plt.plot(x, y, 'r', linewidth=2)
  11. plt.ylim(ymin=0)
  12. # Make the shaded region
  13. ix = np.linspace(a, b)
  14. iy = func(ix)
  15. verts = [(a, 0), *zip(ix, iy), (b, 0)]
  16. poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
  17. ax.add_patch(poly)
  18. plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
  19. horizontalalignment='center', fontsize=20)
  20. plt.figtext(0.9, 0.05, '$x$')
  21. plt.figtext(0.1, 0.9, '$y$')
  22. ax.spines['right'].set_visible(False)
  23. ax.spines['top'].set_visible(False)
  24. ax.xaxis.set_ticks_position('bottom')
  25. ax.set_xticks((a, b))
  26. ax.set_xticklabels(('$a$', '$b$'))
  27. ax.set_yticks([])
  28. plt.show()

下载这个示例