向 GGPlot 折线图添加平均条形

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

我正在为一个项目的手稿制作图表,我是统计学家,想知道是否有人可以帮助我重新创建图表。

我不允许分享真实数据,所以我只会创建一个示例数据集:


set.seed(123)

record_id <- rep(1:20, each = 2)

visit <- rep(1:2, times = 20)

treatment <- rep(sample(c("AB", "BA"), 20, replace = TRUE), each = 2)

trt_seq <- ifelse(treatment == "AB" & visit == 1, "A", 
                  ifelse(treatment == "AB" & visit == 2, "B",
                         ifelse(treatment == "BA" & visit == 1, "B", "A")))

O2 <- rnorm(40, mean = 30, sd = 5)

sample_data <- data.frame(
  Record_ID = record_id,
  Visit = visit,
  Treatment = treatment,
  Trt_Seq = trt_seq,
  O2 = O2
)

这基本上就是我的数据的样子。实际效果并不重要,我只是想在可视化中添加一些东西。

library(ggplot2)
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
# This is colorblind friendly colors for ggplot

ggplot(sample_data, 
       aes(factor(Trt_Seq), O2, 
           group = record_id,
           color = Treatment)) +
  geom_point(size = 2) +
  geom_line() +
  scale_colour_manual(values = cbPalette) + 
  theme_bw(base_size = 16) +
  ylim(0, 45) +
  ylab("Peak O2") +
  xlab("Treatment") + 
  ggtitle("Peak O2 Treatment Effect")

example_graph_output 这就是它的样子!抱歉,我不知道如何使图表与文本完全一致?

我想知道如何使它看起来像这样: Example_graph_goal

如果有人有什么可以推荐的,我将非常感激!我相信我想要的图表来自 Prism(医生倾向于使用的东西),但我正在使用 Rstudio,所以我希望得到任何和所有帮助。

我尝试使用 geom_segment 或 geom_hline 添加参数?但它们并没有真正发挥作用。

mean_O2 <- aggregate(O2 ~ Treatment, data = sample_data, FUN = mean)

ggplot(sample_data, 
       aes(factor(Trt_Seq), O2, 
           group = record_id,
           color = Treatment)) +
  geom_point(size = 2) +
  geom_line() +
   geom_segment(data = mean_O2, aes(x = as.numeric(factor(Treatment)) - 0.2, 
       xend = as.numeric(factor(Treatment)) + 0.2, 
      y = O2, yend = O2), color = "black", size = 0.5) +

  scale_colour_manual(values = cbPalette) + 
  theme_bw(base_size = 16) +
  ylim(0, 45) +
  ylab("Peak O2") +
  xlab("Treatment") + 
  ggtitle("Peak O2 Treatment Effect")

添加了这个,但它只是给了我奇怪的垂直线。

请帮助我!!

r ggplot2 plot charts
1个回答
0
投票

这是实现您想要的结果的一种可能的选择,它使用

dplyr::reframe
ggplot2::mean_se
获取平均值和标准误差的数据框,然后使用
geom_errorbar
geom_point
将它们添加到您的图中:

library(ggplot2)
library(dplyr, warn = FALSE)

mean_O2 <- sample_data |>
  reframe(mean_se(O2, mult = 2), .by = Treatment) |>
  mutate(
    x = as.numeric(factor(Treatment)),
    x = x + .3 * if_else(x == 1, -1, 1)
  )

ggplot(
  sample_data,
  aes(factor(Trt_Seq), O2,
    group = record_id,
    color = Treatment
  )
) +
  geom_point(size = 2) +
  geom_line() +
  geom_errorbar(
    data = mean_O2,
    aes(x = x, y = y, ymin = ymin, ymax = ymax, group = 1),
    width = .1
  ) +
  geom_point(
    data = mean_O2,
    aes(x = x, y = y, group = 1)
  ) +
  scale_colour_manual(values = cbPalette) +
  theme_bw(base_size = 16) +
  ylim(0, 45) +
  ylab("Peak O2") +
  xlab("Treatment") +
  ggtitle("Peak O2 Treatment Effect")

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