Python Matplotlib 绘制折线图并添加标注点,坐标轴为字符

使用 Python Matplotlib 库可以轻松绘制折线图并添加标注点,同时还可以设置坐标轴为字符类型。以下代码演示了如何实现这个功能,并解决代码中出现的错误。

import matplotlib.pyplot as plt

x1 = ['1', '2', '3', '4', '5']
y11 = [10, 8, 7, 5, 9]
y21 = [3, 5, 6, 2, 4]
markers1 = [2, 4]

fig, ax = plt.subplots()
ax.plot(x1, y11, color='b', marker='o', markersize=12, label='y11')
ax.plot(x1, y21, color='r', marker='s', markersize=12, label='y21')

for i in markers1:
    ax.plot(x1[i-1], y21[i-1], color='r', marker='s', markersize=12)
    ax.annotate(f'y21[{i}]', xy=(x1[i-1], y21[i-1]), xytext=(-10, 10), textcoords='offset points', ha='center', va='bottom')

ax.set_xticklabels(x1)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()

plt.show()

代码解释:

  1. 导入 matplotlib 库: import matplotlib.pyplot as plt
  2. 定义数据: x1, y11, y21 分别代表横坐标、纵坐标1、纵坐标2,markers1 是需要添加标注点的索引列表。
  3. 创建画布和坐标轴: fig, ax = plt.subplots()
  4. 绘制折线图: ax.plot(x1, y11, color='b', marker='o', markersize=12, label='y11')ax.plot(x1, y21, color='r', marker='s', markersize=12, label='y21') 分别绘制两条折线,并设置颜色、标记、大小和标签。
  5. 添加标注点: 使用循环遍历 markers1,并使用 ax.plot(x1[i-1], y21[i-1], color='r', marker='s', markersize=12) 在对应位置添加标注点。
  6. 添加标注文字: 使用 ax.annotate(f'y21[{i}]', xy=(x1[i-1], y21[i-1]), xytext=(-10, 10), textcoords='offset points', ha='center', va='bottom') 添加标注文字,并设置文字内容、位置和偏移量。
  7. 设置坐标轴标签: ax.set_xticklabels(x1) 设置横坐标刻度标签,ax.set_xlabel('x')ax.set_ylabel('y') 设置坐标轴标签。
  8. 添加图例: ax.legend() 添加图例。
  9. 显示图形: plt.show() 显示生成的图形。

错误解析:

代码中出现的错误 TypeError: list indices must be integers or slices, not str 是因为 x1 是一个字符列表,而 i 是一个整数,不能直接作为列表索引使用。解决方案是在使用 x1[i] 时,先将 i 转化为整数,例如 x1[int(i)]

输出结果:

折线图

该图形展示了两个折线图,其中两个标注点分别标注在 y21 的第二和第四个点上,坐标轴使用字符类型表示。

总结:

使用 Python Matplotlib 库绘制折线图并添加标注点,同时设置坐标轴为字符类型非常简单。通过合理设置参数和代码逻辑,可以轻松实现所需的功能。

更多学习资源:

Python Matplotlib 绘制折线图并添加标注点,坐标轴为字符

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

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