无法使用R中的ggplot2更改图例标题和标签

无法使用R中的ggplot2更改图例标题和标签,r,ggplot2,label,legend,R,Ggplot2,Label,Legend,我试图将图例标题从group改为希腊字母“sigma”,将标签“power.1,power.2,power.3”改为“35,40,45”,但它没有出现,仍然显示默认名称和标签。你能帮我吗?非常感谢 # Load the library and input the data library(ggplot2) library(tidyr) n <- 2:10 control <- rep(150, 4) infected <- c(150, 170, 200, 250) all

我试图将图例标题从group改为希腊字母“sigma”,将标签“power.1,power.2,power.3”改为“35,40,45”,但它没有出现,仍然显示默认名称和标签。你能帮我吗?非常感谢

# Load the library and input the data
library(ggplot2)
library(tidyr)

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)

data <- data.frame(n, power.1, power.2, power.3)

data %>%
  pivot_longer(cols = contains("power"), names_to = "group", values_to = "power") %>%
  ggplot(aes(n, power)) +
  geom_line(aes(color = group)) +
  geom_point(aes(color = group), size = 4) +
  scale_fill_discrete(name = expression(sigma), labels = c("35","40","45"))
#加载库并输入数据
图书馆(GG2)
图书馆(tidyr)

n在代码的最后一部分尝试这个。你可以学到的一个教训是填充和颜色是不同的美学。因此,如果设置颜色,则必须使用
scale\u color\u manual
。代码如下:

#Code
data %>%
  pivot_longer(cols = contains("power"), names_to = "group", values_to = "power") %>%
  ggplot(aes(n, power)) +
  geom_line(aes(color = group)) +
  geom_point(aes(color = group), size = 4) +
  scale_color_discrete(name = expression(sigma), labels = c("35","40","45"))
输出:

或者您也可以尝试使用
guides()
,这将产生相同的输出(但第一个选项更直接):

您应该使用:

scale_colour_discrete(name = expression(sigma), labels = c("35","40","45"))

感谢您的帮助和第二个代码。非常感谢。
scale_colour_discrete(name = expression(sigma), labels = c("35","40","45"))