是否可以在ggplot geom_density_ridges中可视化组?

mfuanj7w  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(82)

我已经建立了一个很好的图表,显示了一周中每天的时间模式。
在一周中的每一天的每条曲线中,我想按组可视化数据。分组应该发生在列“ID”,我可以设置为True/False或A/B或任何最好的。理想情况下,每张图将由两种不同的颜色组成,清楚地显示哪一组主要负责某些峰值。这意味着一组数据点位于底部,另一组堆叠在顶部。
color = ID, fill = ID没有工作。
你知道我是怎么做到的吗?

ggplot(aes(x = weekdaytime, y = weekday, fill = weekday, group = weekday, height = ..count..)) +
  geom_density_ridges_gradient(stat = "density", scale = 2, rel_min_height = 0.01, bw = 300 ) +
  scale_fill_viridis(name = "", option = "C") +
  scale_x_datetime(date_breaks = "2 hour", date_labels = "%H", 
                   limits = as.POSIXct(strptime(c(paste(Sys.Date(), "00:00", sep=" "),
                                                  paste(Sys.Date(), "24:00", sep=" ")), 
                                                format = "%Y-%m-%d %H:%M"))) +
  scale_y_discrete(limits=c("Monday", "Tuesday", "Wednesday", "Thursday", 
                            "Friday", "Saturday", "Sunday"))+
  theme(
    legend.position="none",
    panel.spacing = unit(0.1, "lines"),
    panel.grid.major = element_line(colour = "grey"),
    panel.grid.minor = element_line(colour = "grey"),
    
    panel.background = element_blank(),
    strip.text.x = element_text(size = 7)
  )  ```
cpjpxq1n

cpjpxq1n1#

如果您在aes()中引入另一个因素(例如颜色或形状),它将改变密度曲线的数量,例如,使用palmerpenguins dataset

library(tidyverse)
library(palmerpenguins)
library(ggridges)

penguins %>%
  na.omit() %>%
  ggplot(aes(x = body_mass_g, y = species)) +
  geom_density_ridges(
    alpha = .2, point_alpha = 1, jittered_points = TRUE
  )
#> Picking joint bandwidth of 153

penguins %>%
  na.omit() %>%
  ggplot(aes(x = body_mass_g, y = species)) +
  geom_density_ridges(
    aes(point_color = island),
    alpha = .2, point_alpha = 1, jittered_points = TRUE
  ) +
  theme(legend.position = "none")
#> Picking joint bandwidth of 172

创建于2023-05-18带有reprex v2.0.2
因此,对于阿德利企鹅,绘制了“群体”(起源岛),但您有三条密度曲线,而不是第一张图中的单条曲线。
一个可能的解决方法是使用两个geom_density_ridges()调用分别绘制脊和点,例如:

library(tidyverse)
library(palmerpenguins)
library(ggridges)

penguins %>%
  na.omit() %>%
  ggplot(aes(x = body_mass_g, y = species)) +
  geom_density_ridges() +
  geom_density_ridges(
    aes(point_color = island),
    alpha = 0, color = NA, point_alpha = 1, jittered_points = TRUE
  ) +
  theme(legend.position = "none")
#> Picking joint bandwidth of 153
#> Picking joint bandwidth of 172

创建于2023-05-18带有reprex v2.0.2
这种方法是否适用于您的用例?

相关问题