首页 > 解决方案 > 如何将 python matplotlib.pyplot 图例标记更改为 1、2、3 之类的序列号,而不是形状或字符?

问题描述

import matplotlib.pyplot

plt.figure() 
plt.plot(x, 'r+', label='one')
plt.plot(x1, 'go--', label ='two')
plt.plot(y, 'ro', label='Three')
plt.legend()

在上面的代码中,图例标记是 'r+' , 'go--' 和 'ro' 但我希望它变成 1,2 和 3,因为有 3 个图。?谁能帮我解决这个问题?还有什么方法可以在不对数字进行硬编码的情况下完成吗?“““ 谢谢。

标签: python-3.xmatplotlibmatplotlib-basemapmatplotlib-widget

解决方案


您可以使用生成器(例如,itertools.count)和next

import matplotlib.pyplot

x=x1=y=(0,0) # dummy data

markers = iter(['r+', 'go--', 'ro'])

plt.figure() 
plt.plot(x, next(markers), label='1')
plt.plot(x1, next(markers), label='2')
plt.plot(y, next(markers), label='3')
plt.legend()

输出:

示例图


推荐阅读