Skip to main content
 首页 » 编程设计

python之在 plt.plot() 命令之外定义绘图标签之Matplotlib

2024年11月01日7leader

我正在制作一个散点图,它根据数据中的条件使用两个不同的符号。 在遍历数据行的 for 循环中,如果满足条件,则用圆圈绘制点,如果不满足,则用正方形绘制点:

for i in thick.index: 
    if thick['Interest'][i] == 1: 
        plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 'o', color = 'b') 
    else: 
        plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 's', color = 'r') 

其中“兴趣”是一个用 1 和 0(零?)填充的列。

我想在图例中为圆圈添加一个标签,为正方形添加一个标签,但是如果我在 plt.scatter(. ..) 命令我在图例中得到的行数与我的数据文件中的行数一样多。

我是否缺少一个简单的技巧?

谢谢。

请您参考如下方法:

这是我在这种情况下使用的模式:

label_o = 'Circle' 
label_s = 'Square' 
for i in thick.index: 
    if thick['Interest'][i] == 1: 
        plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker=o', color='b', label=label_o) 
        label_o = None 
    else: 
        plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker='s', color='r', label=label_s) 
        label_s = None 

这也很好地处理了只有一个类别存在的情况。