简体   繁体   中英

Modify a legend in ggplot2

Good afternoon everyone, I have a question about ggplot2.

Here is a simplified version of my problem I have a graphic with four lines with a color for each line.

My code is :

 library(ggplot2)
 df=data.frame(x=1:20,
              y=rep(1:5,4),
              ind=c(rep(1,5),rep(2,5),rep(3,5),rep(4,5))
)

p=ggplot(data=df, aes(x=x,y=y,group=ind, colour=factor(ind))) +
  geom_line() +
  scale_colour_manual(name="",
                      values=c("blue4","green4","blue3","green3"), 
                      labels=c("type1","type1","type2","type2"), 
                      breaks=c("1","3","2","4"))

However the blue lines and the green lines stand for a same characteristic, so I would like a legend with only two boxes instead of four : one referring to the blue lines, and the other one reffering to the green lines. The following code shows you a graphic with the kind of legend I want :

plot(x=1:5, y=1:5, col="blue4", type="l", xlim=c(0,20))
lines(x=6:10, y=1:5, col="green4")
lines(x=11:15, y=1:5, col="blue3")
lines(x=16:20, y=1:5, col="green3")
legend("topright", legend=c("type1","type2"), col=c("blue3","green3"), lty=c(1,1))

You might say that I should do it the classic way (ie not using ggplot2), nevertheless my real case is more technically advanced, hence I really need to use ggplot2 (in order to control more easily other graphic parameters).

I'm sorry if you can't see my graphics. My inteded to post them but I can't due to not enough reputation point Thanks in advance if you can help me. Maël

You can create a new factor with two levels (instead of four) and use this factor as argument for the colour parameter in the plot.

The new factor ind2 has the label type1 where ind is odd and type2 where ind is even.

df$ind2 <- factor(!df$ind %% 2, labels = c("type1", "type2"))

ggplot(data = df, aes(x = x, y = y, group = ind, colour = ind2)) +
  geom_line() +
  scale_colour_manual(values=c("blue4", "green4"))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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