如何修改Matplotlib标注代码:用标记替代箭头标注局部最大值
用标记替代箭头标注Matplotlib中的局部最大值
没问题,咱们把箭头换成醒目的标记来标注局部最大值很容易,直接用散点图工具绘制标记,再配合纯文本标注就可以啦。修改后的完整代码如下:
import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) x=[1,2,3,4,5,6,7,8,9,10] y=[1,1,1,2,10,2,1,1,1,1] line, = ax.plot(x, y) ymax = max(y) xpos = y.index(ymax) xmax = x[xpos] # 用红色五角星标记标注最大值点,可自定义样式 ax.scatter(xmax, ymax, marker='*', color='red', s=100, zorder=5) # 添加文本说明,不带箭头,居中对齐 ax.annotate('local max:' + str(ymax), xy=(xmax, ymax + 2), ha='center') plt.show()
关键修改说明:
- 用
ax.scatter()替代箭头:这里选了marker='*'(五角星),你还可以换成其他标记样式,比如'o'(实心圆)、'^'(上三角);s=100控制标记大小,zorder=5确保标记显示在折线的上方,不会被线条挡住。 - 简化
annotate:去掉了arrowprops参数,只保留文本标注,ha='center'让文本在x轴方向上和最大值点居中对齐,位置设置在最大值点上方2个单位,避免遮挡数据点。
内容的提问来源于stack exchange,提问作者Artur Müller Romanov
相关产品推荐
相关产品推荐

