首页 > 解决方案 > 使用 R 在 ggplot2 中添加图例

问题描述

在绘制样本大小与功率的关系图时,我在用 ggplots 添加 R 中的图例时遇到问题。我试过 guide_legend() 但它失败了。非常感谢你的帮助。

# Load the library and input the data
library(ggplot2)
n <- 2:10
control <- rep(150, 4)
infected <- c(150, 170, 200, 250)
all <- c(control, infected)
sigma <- c(35, 40, 45)

# Compute the population mean
mu <- mean(all)
# Compute the sum of the tau squared
tau2 <- sum((all-mu)^2)
# Compute the gamma
gamma.1 <- (n*tau2)/(sigma[1]^2) 
gamma.2 <- (n*tau2)/(sigma[2]^2) 
gamma.3 <- (n*tau2)/(sigma[3]^2) 
# Compute the power
power.1 <- 1-pf(qf(.95, 7, 16), 7, 16, gamma.1)
power.2 <- 1-pf(qf(.95, 7, 16), 7, 16, gamma.2)
power.3 <- 1-pf(qf(.95, 7, 16), 7, 16, gamma.3)

# Plot the power vs the sample size
data <- data.frame(n, power.1, power.2, power.3)
ggplot(data, aes(x = n)) +
geom_point(aes(y=power.1), size = 3.5, color = "blue") +
geom_line(aes(y=power.1), size = 0.5) +
geom_point(aes(y=power.2), size = 3.5, color = "red") +
geom_line(aes(y=power.2), size = 0.5) +
geom_point(aes(y=power.3), size = 3.5, color = "black") +
geom_line(aes(y=power.3), size = 0.5) +  
xlab("Sample Sizes") +
ylab("Power") +
ggtitle("Power versus Sample size")

在此处输入图像描述

标签: rggplot2legend

解决方案


您可以将数据转换为很适合绘图的长格式,因为这样您就有了分组变量(列的名称是组):

data %>%
  pivot_longer(cols = contains("power"), names_to = "group", values_to = "power") %>%
  ggplot(aes(n, power)) +
  geom_line(aes(group = group)) +
  geom_point(aes(color = group), size = 4) +
  scale_color_manual(values = c("blue", "red", "black"))

在此处输入图像描述

我还在点之前添加了行。


推荐阅读