r 中的 stat_difference 函数不起作用

问题描述 投票:0回答:1

尝试填充两条线之间的颜色。但这不起作用。

我尝试了两种方法。

第一个:

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()

第二个是:


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))
r ggplot2 visualization ggh4x
1个回答
0
投票

我按照文档中的示例进行操作,它也适用于您的数据。我刚刚创建了使月份按顺序排列的因子。

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))

创建于 2024-04-13,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.