Ai4l2s
Ai4l2s

Reputation: 623

R: Remove text in ggplot2 bar plot if value is less than a threshhold

I have the following plot:

df <- tibble(days = c(1, 1, 2, 2),
         type = c("v1", "v2", "v1", "v2"),
         values = c(100, 1, 2, 200))
plot <-  df %>%
  ggplot(aes(days, values, fill = factor(type))) + 
  geom_bar(stat = 'identity',  position = 'dodge') + 
  geom_text(aes(label = values), vjust=1.6, color="white", position = position_dodge(0.9), size=3.5)
plot

Is there any way to only add text on a bar, if the corresponding value is greater than a specific threshhold. In this case, I want to remove the text "1" and "2" (blue circles).

enter image description here

Upvotes: 1

Views: 599

Answers (1)

LulY
LulY

Reputation: 1294

Use a new variable for geom_text which you set to NA if under the treshhold.

library(tidyverse)
df <- tibble(days = c(1, 1, 2, 2),
         type = c("v1", "v2", "v1", "v2"),
         values = c(100, 1, 2, 200))
tresh <- 100
df$text <- ifelse(df$values < tresh, NA, df$values)

plot <-  df %>%
  ggplot(aes(days, values, fill = factor(type))) + 
  geom_bar(stat = 'identity',  position = 'dodge') + 
  geom_text(aes(label = text), vjust=1.6, color="white", position = position_dodge(0.9), size=3.5)
plot

pl

Upvotes: 1

Related Questions