ggplot2中斜率的线条颜色和宽度

时间:2018-05-04 19:16:59

标签: r ggplot2 tidyverse

这与this question以及this非常密切相关,至少在这种背景下,我不理解这些答案。我想通过基于其斜率在线上放置热图样式渐变来区分增加和减少分数(例如,从T1到T2的重复心理测量)。换句话说,我想使用例如Viridis的地域尺度,使得最急剧减少的线倾向于黑暗,而最急剧增加的线倾向于光。

非常感谢任何想法!

data <- data.frame(id = 1:500, 
                               Intrinsic_01_T1 = sample(1:5, 500, replace = TRUE), 
                               Intrinsic_02_T1 = sample(1:5, 500, replace = TRUE), 
                               Intrinsic_03_T1 = sample(1:5, 500, replace = TRUE), 
                               Intrinsic_01_T2 = sample(1:5, 500, replace = TRUE, prob = c(0.1, 0.1, 0.2, 0.3, 0.3)), 
                               Intrinsic_02_T2 = sample(1:5, 500, replace = TRUE), 
                               Intrinsic_03_T2 = sample(1:5, 500, replace = TRUE, prob = c(0.3, 0.3, 0.2, 0.1, 0.1)))

pd <- position_dodge(0.4)

data %>% 
  tidyr::gather(variable, value, -id) %>% 
  tidyr::separate(variable, c("item", "time"), sep = "_T") %>% 
  dplyr::mutate(value = jitter(value, amount = 0.1)) %>% # Y-axis jitter to make points more readable
ggplot(aes(x = time, y = value, group = id)) +
  geom_point(size = 1, alpha = .2, position = pd) +
  geom_line(alpha = .2, position = pd) +
  ggtitle('Multiple indicator LCS model') + 
  ylab('Intrinsic motivation scores') +
  xlab('Time points') + 
  facet_wrap("item")

The resulting figure

1 个答案:

答案 0 :(得分:2)

诀窍是在绘图之前计算每条线的斜率。为此,您可以group by时间和项目,然后计算每条线的斜率。

data %>% 
  tidyr::gather(variable, value, -id) %>% 
  tidyr::separate(variable, c("item", "time"), sep = "_T") %>% 
  dplyr::mutate(value = jitter(value, amount = 0.1)) %>%  # Y-axis jitter to make points more readable
  group_by(id,item) %>% 
  mutate(slope = (value[time==2] - value[time==1])/(2-1)) %>% 
  ggplot(aes(x = time, y = value, group = id)) +
  geom_point(size = 1, alpha = .2, position = pd) +
  geom_line(alpha = .2, position = pd, aes(color = slope)) +
  scale_color_viridis_c(option = "inferno")+
   ggtitle('Multiple indicator LCS model') + 
  ylab('Intrinsic motivation scores') +
  xlab('Time points') + 
  facet_wrap("item")

导致:

enter image description here