这里提供一个使用 matplotlib 库绘制多条曲线并在线上添加注释的 Python 代码示例:

import matplotlib.pyplot as plt

# 定义 x 和 y 值
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [1, 4, 9, 16, 25]
y3 = [1, 8, 27, 64, 125]

# 绘制三条曲线
plt.plot(x, y1, label='y = x')
plt.plot(x, y2, label='y = x^2')
plt.plot(x, y3, label='y = x^3')

# 在曲线上添加注释
plt.annotate('y = x', xy=(1, 1), xytext=(2, 3),
             arrowprops=dict(facecolor='black', shrink=0.05))
plt.annotate('y = x^2', xy=(4, 16), xytext=(3, 20),
             arrowprops=dict(facecolor='black', shrink=0.05))
plt.annotate('y = x^3', xy=(5, 125), xytext=(4, 100),
             arrowprops=dict(facecolor='black', shrink=0.05))

# 设置图例
plt.legend()

# 显示图形
plt.show()

代码中首先定义了 x 和三组 y 值,然后使用 plt.plot() 函数绘制了三条曲线,并使用 label 参数为每条曲线添加标签。接着使用 plt.annotate() 函数为每条曲线添加注释,其中 xy 参数指定注释箭头所在的点,xytext 参数指定注释文本所在的点,arrowprops 参数指定注释箭头的样式。最后使用 plt.legend() 函数设置图例并使用 plt.show() 函数显示图形。


原文地址: https://www.cveoy.top/t/topic/bcQU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录