2
votes

Consider the following example (taken from another post on Stackoverflow):

require(ggplot2)
d <- data.frame(x = c(102856,17906,89697,74384,91081,52457,73749,29910,75604,28267,122136, 54210,48925,58937,76281,67789,69138,18026,90806,44893),
y = c(2818, 234, 2728, 2393, 2893, 1015, 1403, 791, 2243, 596, 2468, 1495, 1232, 1746, 2410, 1791, 1706, 259, 1982, 836),
names = c("A","C","E","D","G","F","I","H","K","M","L","N","Q","P","S","R","T","W","V","Y"))
ggplot(d, aes(x,y,col=names)) + geom_point() + geom_text(aes(label=names),hjust=1,vjust=1)

Running it with and then without the last "geom_text" layer changes the legend (The bullet becomes a bullet with another symbol superposed on it).

Could you explain me why, and how I can avoid this change ? Thanks.

1

1 Answers

7
votes

As you set color= inside the ggplot() call, colors are used for the points and for the text labels and also legend is made for points (default symbol is point) and texts (default symbol is a). If you add something in aes() of ggplot() then it affects all layers that uses such parameter, if new argument isn't added to that layer. If you need to change color for text labels but don't want to show in legend then add argument show_guide=FALSE inside the geom_text().

ggplot(d, aes(x,y,color=names)) + geom_point() + 
  geom_text(aes(label=names),hjust=1,vjust=1,show_guide=FALSE)

If you want to change color only for the points then color= argument should be placed in aes() of geom_point(), so it will affect colors only of points.

ggplot(d, aes(x,y)) + geom_point(aes(color=names)) + 
  geom_text(aes(label=names),hjust=1,vjust=1)