如何在matplotlib中绘制线图上的最大值点?

1 投票
1 回答
6875 浏览
提问于 2025-04-18 14:21

我现在在用Python 3.4,想知道怎么用matplotlib这个库在我当前的线性图上标出最大值的点。我的图很简单:有两条线,y轴是分数,x轴是时间。我想在每条线的最大分数对应的时间点上标出一个点,并显示这个点的坐标:也就是(最佳时间,最大分数)。有没有人知道用matplotlib能不能做到这一点?谢谢大家!

1 个回答

1

我最后做的是使用两个图表(time_list是x轴的值,score是y轴的值列表):

ordered_time = [time_list for (score,time_list) in sorted(zip(score,time_list))]
best_time = ordered_time[-1]
max_coords = '('+str(best_time)+', ' + str("%.4f" % (max(score)))+')'
max_point = pl.plot(best_time, max(score), 'bo', label="(Opt. Time, Max Score)")
pl.text(best_time, max(score), max_coords)
... (insert rest of stuff for your graph)

这个方法会找到特定线上的最大点,然后在这个点上画一个点,并用坐标给这个点标注。

如果你想用其他文字标签而不是坐标,只需在最后一行把“max_coords”替换成你想要的任何字符串就可以了。

如果你想找到每条线的最大值,那么只需准备多个x和y列表,然后重复同样的过程(例如,不用“time_list”和“score”,而是用“time_list_1”、“time_list_2”等,以及“score_1”、“score_2”等...)

希望这对某些人有帮助。

撰写回答