# How can I add a legend

Hi!

I plot a data, for example y = [1, 2, 3, 999, 34, 35, 34, 23, 345, 234, 23] and with classes=[1, 2, 1, 2, 3, 1, 2, 3, …]
Then I write:
plot(x, y, linecolor = classes)
So I get a plot with one line with three different colours (like a piecewise line).

The question is how can label three different colours since when I use plot(label = [“1” “2” “3”]), the plot only shows “1” since there is actually one line. Thanks a lot!

1 Like

Welcome @bayerndd,

which plotting package are you using and please check

1 Like

Hi! I am using Plots only

I think, what you want is not possible in a more or less single plot command.
The way to go is to decompose the single line into pieces for each color and plot them successively into the same plot.
Here is how I solved it:

``````using Plots

function decompose(classes,c)
r1=falses(length(classes)+1)
r2=falses(length(classes)+1)
b=0
for i in 1:length(classes)
if classes[i]==c
if b==0
b=1
r1[i]=true
r1[i+1]=true
else
b=0
r2[i]=true
r2[i+1]=true
end
else
i>1&&!r1[i-1] ? r1[i]=false : nothing
i>1&&!r2[i-1] ? r2[i]=false : nothing
end
end
(r1,r2)
end

x=1:11   #x-axis
y = [1, 2, 3, 999, 34, 35, 34, 23, 345, 234, 23]  #y-axes 11 points
classes=[1, 2, 1, 2, 3, 1, 2, 3, 2, 3]  # 11 points define 10 lines => 10 color entries

yp1=Array{Union{Missing, Int64}}(undef,length(y))
yp2=Array{Union{Missing, Int64}}(undef,length(y))

p=plot()
for c in sort(unique(classes))
#global p #not needed
yp1.=missing
yp2.=missing
yp1[decompose(classes,c)]=y[decompose(classes,c)]
yp2[decompose(classes,c)]=y[decompose(classes,c)]
plot!(p,x,yp1,linecolor=c,label=c)
plot!(p,x,yp2,linecolor=c,label=nothing)
end
display(p)
`````` 2 Likes