r - ggplot2 geom_errorbar 具有实心须线和位置躲避

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

尝试遵循此问题中建议的解决方案。

ggplot2 geom_errorbar 具有不同的线型,但具有实心须线

不幸的是,当同时使用位置闪避时,会发生一些奇怪的事情。

library(ggplot2)
library(dplyr)

dat <- data.frame(cohort = rep(c("Placebo", "Trt 1", "Trt 2"), times = 3),
                  visit = c(rep("Baseline", times = 3), rep("Time 2", times = 3), rep("Time 3", times = 3)),
                  visitnum = c(rep(1, times = 3), rep(2, times = 3), rep(3, times = 3)),
                  mean = rnorm(9)
                  ) %>% 
  mutate(lower = mean - 1,
         upper = mean + 1)

dodge <- position_dodge2(.25)

dat %>% ggplot(aes(x = visitnum, y = mean, color = cohort, group = cohort, linetype = cohort)) +
  geom_line(position = dodge) +
  geom_point(position = dodge) +
  geom_linerange(aes(ymin = lower, ymax = upper),
                 position = dodge) +
  geom_segment(aes(x = visitnum-.1, xend = visitnum+.1, y = lower, yend = lower), position = dodge, linetype = "solid") +
  geom_segment(aes(x = visitnum-.1, xend = visitnum+.1, y = upper, yend = upper), position = dodge, linetype = "solid") +
  
  scale_linetype_manual(values = c("solid", "solid", "dotted")) +
  
  scale_x_continuous(breaks = unique(dat$visitnum), labels = unique(dat$visit))

geom_segment 创建的线条似乎已正确调整。

剧情

任何帮助将不胜感激。

r ggplot2
1个回答
0
投票

您可以将最后三层替换为:

geom_errorbar(aes(ymin = lower, ymax = upper),
                position = position_dodge(width = 0.25), width = 0.25) +

enter image description here

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