0

I have created a graph in R with ggplot, which shows the different groups of phytoplankton over the years. Now it have been requested to remove a group from the legend, because they cannot really been seen in the graph (for eg. "Cyanobacteria"). My question is this possible? If yes how?

My data:

data phytoplankton

My code:

if(!require(pacman)){install.packages("pacman")}
pacman::p_load(DT,leaflet,leaflet.extras,readxl,htmlwidgets,plotly,dplyr,lubridate,vegan,zoo,
               ggplot2,reshape2,sciplot,psych,RColorBrewer)

df<-read_excel("C:/wherever")

attach(df)

 
colourCount=length(unique(df$Phytoplankton))
getPalette = colorRampPalette(brewer.pal(12, "Paired"))

p<-ggplot(data=df, aes(x=Year, y=Abu, fill=Phytoplankton))+geom_bar(stat="identity",color="black", width =1)

p<-p+scale_fill_manual(values = getPalette(colourCount))

p<-p+labs(title="Phytoplanktondichte",x="Jahr", y = "Individuendichte (Ind/L)")

p<-p+theme_minimal()

p

I found out how to change the colour, the position, the title basically everything, but I coundn´t fine anything in how to remove something from the legend.

I would really appreciate your help.

benson23
  • 16,369
  • 9
  • 19
  • 38
anna
  • 1
  • Please, check [How to make a great R reproducible example](https://stackoverflow.com/q/5963269/13818750) – ahmathelte Feb 28 '22 at 17:09
  • 1
    The obvious answer here is that if you want to remove an item from the legend because its data points are not visible in the plot, you should just remove those items from the data you are using to plot. `ggplot(df[df$phytoplanton != "cyanobacteria",], ...)` – Allan Cameron Feb 28 '22 at 17:10

1 Answers1

3

If you want unidentified elements in your graph (they are plotted but not labeled in the legend), you can specify what values you want in the legend in the breaks argument while still specifying all scale values as a named vector:

ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point() +
  scale_color_manual(
    breaks = c("4", "6"),
    values = c("4" = "orange", "6" = "blue", "8" = "purple")
  )

enter image description here

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294