Home > Mobile >  ggplot 2 bar chart, indicate that bar is NA instead of 0
ggplot 2 bar chart, indicate that bar is NA instead of 0

Time:01-04

I am making a bar chart showing root area at several depths across of series of dates. My dataset includes boths NAs and 0s for the root area at several depths and I want to indicate a difference between 0s and NAs by labeling these blank areas either NA or 0. Is there a way to do this in ggplot?

My current code is below and while it works to show changes in root area over time it does not indicate whether a blank area is a 0 or NA. I am really not sure how to approach this problem. Any help would be much appreciated.

ggplot(data=df, aes(x=Depth, y=RootArea, fill=Date))  
  geom_bar(stat="identity", position=position_dodge())

CodePudding user response:

Using e.g. dplyr::case_when you could first add a column with your desired labels for NAs and 0s and blanks for non-NA/non-0 values. Afterwards you could use a geom_text to add these labels to your plot like so.

Using some fake example data:

library(ggplot2)

# Create example data
df <- data.frame(
  Depth = rep(1:4, 2),
  RootArea = c(1, 2, NA, 4, NA, 3, 2, 0),
  Date = rep(c("a", "b"), each = 4)
)


df$label <- dplyr::case_when(
  is.na(df$RootArea) ~ "NA", 
  df$RootArea > 0 ~ "",
  TRUE ~ "0"
)

ggplot(data = df, aes(x = Depth, y = RootArea, fill = Date))  
  geom_col(position = position_dodge())  
  geom_text(
    aes(y = 0, label = label, group = Date),
    position = position_dodge(.9),
    vjust = 0
  )

enter image description here

  • Related