Home > Software engineering >  How to add a function in ggplot2 `scale_...` functions?
How to add a function in ggplot2 `scale_...` functions?

Time:02-25

The following example does not work, but I hope it is helpful to have and idea on what I'm trying to do --- change the label that meets the condition --- E.G., I would like to change one specific label as follows:

scale_color_manual(labels = function(x) {ifelse(x == "Target", as.character("This is the target"), x)})

CodePudding user response:

Your approach seems to work just fine. Please update your question with a minimal reproducible example if the code below doesn't capture your use-case.

library(ggplot2)

df <- data.frame(
  x = c(1:2),
  y = c(1:2),
  col = c("Target", "Schmarget")
)

ggplot(df, aes(x, y, colour = col))  
  geom_point()  
  scale_colour_manual(
    values = c("blue", "red"),
    labels = function(x) {
      ifelse(x == "Target", as.character("This is the target"), x)
    }
  )

Created on 2022-02-24 by the reprex package (v2.0.1)

  • Related