How to specific color of a group of segments ? R ggplot2

Viewed 2698

If I have the sample data and plot it using ggplot2 geom_segment :

library(ggplot2)
df1 <- data.frame(p=c(1,2), f=c("A","B"))
df2 <- data.frame(p=c(3,4), f=c("C","D"))
ggplot() + 
geom_segment(data=df1, mapping=aes(x=p-0.5, xend=p+0.5, y=1, yend=1, color=f)) + 
geom_segment(data=df2, mapping=aes(x=p-0.5, xend=p+0.5, y=1, yend=1, color=f))

the result figure will be : enter image description here

I can't understand why the two separate geom_segment() layers share the same legend? what is the logic behind this behavior?

How can I manually set the color of line "A" and line "B"? I have tried to change them with the following command:

ggplot() + 
geom_segment(data=df1, mapping=aes(x=p-0.5, xend=p+0.5, y=1, yend=1, color=f)) + 
scale_color_manual(values=c("A"="red", "B"="blue")) +  
geom_segment(data=df2, mapping=aes(x=p-0.5, xend=p+0.5, y=1, yend=1, color=f))

but the error message appears :

Error: Insufficient values in manual scale. 4 needed but only 2 provided.

Thanks you very much

1 Answers
Related