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

Fail to change the legend title and label with ggplot2 in R

我试图将图例标题从组更改为希腊字母“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"))

在代码的最后部分试试这个。您可以学到的一课是填充和颜色是不同的美学。因此,如果您设置颜色,则必须使用 scale_color_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(),这将产生相同的输出(但第一个选项更直接):

#Code 2
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(labels = c("35","40","45"))+
  guides(color=guide_legend(title=expression(sigma)))

你应该使用:

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