基于点颜色的朱莉娅散点图图例

问题描述 投票:0回答:1

我正在绘制两个数组,并使用字典将它们的点颜色基于数组中的索引。我现在需要添加图例,但卡住了。

我很重视从两个数组和字典中获取该图的更简洁的方法以及如何添加正确的图例的意见。

这是我的 mwe(实际上我的 x 和 y 有 7255 个条目)。您会看到图例不正确,因为我使用的是循环。

using PyPlot
#dictionary key: index value:category
my_dict=Dict(1 => "male",2 => "female",3=> "male", 4=> "n/a",5 => "male",6 => "female")

#assign colour to index based on category in my_dict
function point_colour(idx, my_dict)
  if my_dict[idx]=="male"
        colour="blue"
    elseif my_dict[idx]=="female"
        colour="red"
    else
        colour="black"
    end
    return colour    
end

 #plot x against y using assigned index colour   
f = figure()
plt.figure(figsize=(14,2.5))
x=[1,2,3,4,5,6]
y=[3,4,5,6,7,8]

for i in 1:length(x)
    col=point_colour(i, my_dict)
    plot(x[i],y[i], "o", color=col, label=my_dict[i])
end

plt.legend()
plt.show()



输出:

plot julia legend
1个回答
0
投票

它会多次添加图例条目,因为您要单独绘制每个点。您有两个选择:

  1. 按标签对点进行分组(即一个数组中的所有男性点),然后使用相应的标签对每个分组列表进行一次绘图调用。

  2. 如果您想像现在一样继续迭代循环,请修改绘图循环以检查它是否已经添加了图例条目,方法如下:

labelled = [] #initialize empty list which we will use to keep track of which things we have labelled
for i in 1:length(x)
    col=point_colour(i, my_dict)
    label = ""
    if my_dict[i] ∉ labelled #get the "not in" symbol by typing \notin + tab at REPL
        label = my_dict[i] #if we haven't already labelled this class, add it to the legend
        push!(labelled,label) #add to our list so we don't label it again
    end
    plot(x[i],y[i], "o", color=col, label=label)
end

您希望它只添加图例条目一次,所以上面的代码所做的是检查您是否已经添加了它,如果是,则不要标记它,但仍然给它正确的颜色。

© www.soinside.com 2019 - 2024. All rights reserved.