簡體   English   中英

如何使用 ggh4x package 將陰影區域添加到行 plot?

[英]How to add shaded area to line plot with the ggh4x package?

我想使用stat_difference()在我的ggh4x中的兩條線之間添加陰影區域。 我已經融化了下面的示例數據集,因為我認為這是facet_wrap我的數據集中所有變量的正確方法,但我不確定如何將stat_difference()與分類變量team一起使用。 我本質上希望對應於Team ATeam B的線根據哪個具有更高的值進行着色,類似於此處的示例。 任何建議都會很棒。 謝謝。

library(tidyverse)
library(ggh4x)
library(reshape2)

set.seed(100)
team <- rep(rep(paste("Team", LETTERS[1:2]), each = 20))
week <- rep(c(1:20), times = 2)

var_1 <- rnorm(n = 40, mean = 20, sd = 5)
var_2 <- rnorm(n = 40, mean = 20, sd = 5)
var_3 <- rnorm(n = 40, mean = 250, sd = 50)
var_4 <- rnorm(n = 40, mean = 100, sd = 50)

dat <- data.frame(team, week, var_1, var_2, var_3, var_4)

plot_dat <- melt(dat, id.vars = c("team", "week"))

ggplot(plot_dat, aes(x = week)) +
  geom_line(aes(y = value, color = team)) +
  facet_wrap(~variable, scales = "free_y")

在您引用的帖子之后,您可以通過使用例如pivot_wider為每個團隊的值創建單獨的列來實現您想要的結果,通過兩個geom_line添加行,然后應用stat_difference

library(tidyverse)
library(ggh4x)
library(reshape2)

plot_dat <- pivot_wider(plot_dat, names_from = team, values_from = value)

ggplot(plot_dat, aes(x = week)) +
  geom_line(aes(y = `Team A`, color = "Team A")) +
  geom_line(aes(y = `Team B`, color = "Team B")) +
  facet_wrap(~variable, scales = "free_y") +
  stat_difference(aes(ymin =  `Team B`, ymax = `Team A`), alpha = 0.3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM