Search code examples
rggplot2axis-labels

Replace axis labels according to their values


I am plotting grouped bar plots using ggplot. I want to replace grouping values with a unique text, depending on their value.

But I get the following warning and the formatting does not work as I want it to. What could be a fix to conditionally replace labels in plots?

1: In if (x == "55") lab = "High" else if (x == "15") lab = "Low" : the condition has length > 1 and only the first element will be used

LabelFormatter <- function (x) {
if (x == "55")
  lab = "High"
else if (x == "15")
  lab = "Low"
}

dF <- data.frame(name=rep(c("A","B","C"),2), value=sample(1:100,6), type=rep(c("15","55"),3))
p <- ggplot (dF, aes(x=type, y=value, fill=name)) + geom_bar(stat="identity", position="dodge")
p <- p + scale_x_discrete(label=LabelFormatter)
print(p)

Solution

  • you can try this

     p+scale_x_discrete(label= c("15"="low", "55"="high"))