0
Data <- data.table(Genotype='Test',Color=c('Ref','NAM','Core Collection'),Group=c('Elite Lines','Core Collection'),V2=c(3000,6000),TrNorm=c(1,2))
Labels <- data.table(LabColor=c('Elite Lines','Core Collection'),Label=c('Label1','Label2'),x=c(1.96,1.96),y=c(5980,5851))

ggplot(data=Data,aes(x=TrNorm,y=V2,color=Color,group=Group)) +
geom_text(data=Labels,aes(x=x,y=y,label=Label,color=LabColor),inherit.aes=F,show.legend=F) + 
geom_point()

As you see, geom_text adds 'Elite Lines' to the legend, which is not supposed to be there as it is not in Data$Color.

enter image description here

Ben
  • 103
  • 1
  • 10
  • Have you loaded packages other than `data.table` and `ggplot2` before running this code? – Zhiqiang Wang Jan 08 '20 at 03:14
  • Yes. many packages. – Ben Jan 08 '20 at 03:44
  • I got the same when there was no other packages loaded. – Ben Jan 08 '20 at 03:46
  • What do you want it to show in the legend? You have both `Color` and `Group` as `aes` in the `ggplot`. – william3031 Jan 08 '20 at 04:04
  • I need group for other layers. I need legend to only show items in Color. – Ben Jan 08 '20 at 04:06
  • remove the color argument from your `geom_text` call. Or change it to `color = Color` – tjebo Jan 08 '20 at 12:18
  • @Tjebo but I nerd the labels to have colours. – Ben Jan 08 '20 at 12:21
  • ggplot adds all elements of your color aesthetics two one legend. You want either to use different aesthetics (such as fill for your points and color for your text) or create two color legends, [such as described here](https://stackoverflow.com/questions/29528915/ggplot2-assign-color-to-2-different-geoms-and-get-2-different-legends/59646193#59646193). Note I have just added an answer with `ggnewscale` which makes this very easy – tjebo Jan 08 '20 at 12:47

1 Answers1

1

The color legend is combining the colors given in the point and text layers. You can set the breaks so that they only include values found in Data$Color:

ggplot(data=Data,aes(x=TrNorm,y=V2,color=Color)) +
  geom_text(data=Labels,aes(x=x,y=y,label=Label,color=LabColor),inherit.aes=F,show.legend=F) +
  geom_point()+
  scale_color_discrete(breaks = unique(Data$Color))
Sarah
  • 3,022
  • 1
  • 19
  • 40
  • My code is much more complicated than this example. Is thete any way to keep the code from combining the colors? – Ben Jan 08 '20 at 07:01