使用R在ggplot2中添加图例

使用R在ggplot2中添加图例,r,ggplot2,legend,R,Ggplot2,Legend,在绘制样本大小与功率的关系图时,我在R中添加带有ggplots的图例时遇到了一个问题。我尝试了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 <-

在绘制样本大小与功率的关系图时,我在R中添加带有ggplots的图例时遇到了一个问题。我尝试了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")
#加载库并输入数据
图书馆(GG2)

n您可以将数据转换为长格式,这对于打印很好,因为这样您就有了分组变量(列的名称是groups):


此外,我在积分前添加了一行。

非常感谢您的帮助,这对我帮助很大。
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"))