简体   繁体   English

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

[英]Define plot label outside plt.plot() command - Matplotlib

I'm making a scatter plot that uses two different symbols based on a condition in the data.我正在制作一个散点图,它根据数据中的条件使用两个不同的符号。 In a for loop iterating through the rows of the data, if a condition is met a point is plotted with a circle, and if not met the point is plotted with a square:在遍历数据行的 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')

where 'Interest' is a column filled with ones and zeros(zeroes?).其中“兴趣”是一列填充有 1 和 0(零?)的列。

I'd like to have one label in the legend for the circles, and one for the squares, but if I declare label = 'circle' in the plt.scatter(...) command I get as many rows in the legend as there rows in my data file.我想在图例中为圆圈设置一个标签,为正方形设置一个标签,但是如果我在plt.scatter(...)命令中声明label = 'circle'我在图例中得到的行数与我的数据文件中有行。

Is there a simple trick I'm missing?我错过了一个简单的技巧吗?

Thanks.谢谢。

This is the pattern I use in such cases:这是我在这种情况下使用的模式:

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

This also nicely takes care of the case where only one of the categories is present.这也很好地处理了仅存在一个类别的情况。

if thick is a data-frame:如果thick是一个数据框:

idx = thick['Interest'] == 1
ax = plt.subplot(111)
ax.scatter(thick['NiThickness'][idx], thick['GdThickness'][idx],
           marker='o', color='b', label='circle')
ax.scatter(thick['NiThickness'][~idx], thick['GdThickness'][~idx],
           marker='s', color='r', label='square')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM