Shilpi Bhargava
Shilpi Bhargava

Reputation: 5

Add a percent symbol to label in specific ggplots and not in other plots

I have a shiny app, with multiple ggplot, few show percent labels others rounded numbers. All are getting returned by same function that creates the ggplot. percent_flag is passed as a parameter to function for same. I tried below logic but it doesnt works. I don't have option of creating additional column to satisfy the creiteria.

geom_text(aes(label = ifelse(percent_flag == 1,
                             paste(round(BIAS_contribution, 2), "%", sep = ""),
                             comma(BIAS_contribution)),
              y = (start + end) / 2)

Upvotes: 0

Views: 711

Answers (1)

mnist
mnist

Reputation: 6954

I would suggest to use a basic if-clause:

library(ggplot2)
percent_flag <- 1

# base plot
p <- iris %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Width))

# with percent flag
if(percent_flag == 1){
  p2 <- p +
  geom_text(aes(label = paste0(Petal.Width, "%")))
  
  # withput percent flag
} else {
  p2 <- p +
    geom_text(aes(label = Petal.Width))
}
p2

Upvotes: 1

Related Questions