rggplot2visualizationggh4x

stat_difference function in r doesn't work


Trying to fill the colors between two lines. But it doesn't work.

I tryied it by two ways.

The first one:

Data <- data.frame(
  Month = c("January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December"),
  Yes = c(9, 8, 7, 11, 7, 11, 9, 8, 9, 10, 4, 7),
  No = c(10, 8, 6, 10, 8, 10, 9, 9, 9, 7, 7, 7)
)

Data_long <- pivot_longer(Data, cols = c(Yes, No), names_to = "Response", values_to = "Count")
Data_long$Month <- factor(AZ_long$Month, levels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"))

ggplot(Data_long, aes(x = Month, y = Count, group = Response)) +
  geom_line(aes(color=Response)) +
  scale_color_manual(values = c("Yes" = "red", "No" = "lightblue")) +
  ggh4x::stat_difference(aes(ymin = AZ_no, ymax = AZ_yes), alpha = 0.3) +
  theme_classic()

And the second one is:


Data <- data.frame(
  Month = c("January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December"),
  Yes = c(9, 8, 7, 11, 7, 11, 9, 8, 9, 10, 4, 7),
  No = c(10, 8, 6, 10, 8, 10, 9, 9, 9, 7, 7, 7)
)

ggplot(data = Data, aes(x = Month, y = Yes)) + 
  geom_line() +
  geom_line(aes(y = No)) +
  ggh4x::stat_difference(aes(ymin = No, ymax = Yes))

Solution

  • I followed the example in the documentation and it worked fine with your data as well. I just created the factor to get the months in order.

    library(ggplot2)
    
    months <- c("January", "February", "March", "April", "May", "June", 
                "July", "August", "September", "October", "November", "December")
    
    dat <- data.frame(
      Month = factor(months, levels = months),
      Yes = c(9, 8, 7, 11, 7, 11, 9, 8, 9, 10, 4, 7),
      No = c(10, 8, 6, 10, 8, 10, 9, 9, 9, 7, 7, 7)
    )
    
    ggplot(data = dat, aes(x = Month, group = 1)) + 
      ggh4x::stat_difference(aes(ymin = No, ymax = Yes)) +
      geom_line(aes(y = Yes)) +
      geom_line(aes(y = No))
    

    Created on 2024-04-13 with reprex v2.1.0