📜  matplotlib 图例数字列 - Python (1)

📅  最后修改于: 2023-12-03 15:02:54.259000             🧑  作者: Mango

Matplotlib 图例数字列 - Python

简介

本文介绍如何在 Matplotlib 中添加数字列来标识每种数据。数字列是一种常用的数据展示方式,可以帮助读者更好地了解数据分布和趋势。

步骤
1. 导入所需的库
import numpy as np
import matplotlib.pyplot as plt
2. 创建示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
3. 绘制图形并添加数字列
fig, ax = plt.subplots()
ax.plot(x, y1, label='sin(x)', color='blue')
ax.plot(x, y2, label='cos(x)', color='red')
for i, y in enumerate([y1, y2]):
    xi = np.argmax(y)
    yi = y[xi]
    ax.annotate('{:.2f}'.format(yi), xy=(xi, yi),
                xytext=(-20, 10), textcoords='offset points',
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
ax.legend()
plt.show()
4. 代码解释
  • ax.annotate() 方法可以在指定位置添加注释文本,并可以设置箭头和注释框的样式。其中,xy 参数指定注释的位置,xytext 参数指定文本的偏移量。

  • enumerate() 方法可以同时遍历序列的索引和值,方便我们获取最大值的位置和数值。

5. 运行结果

Matplotlib 数字列示例

结论

本文介绍了如何在 Matplotlib 中添加数字列来标识每种数据。通过本文的示例,你可以快速上手使用 Matplotlib 绘制带数字列的图表,帮助读者更好地理解数据。