【问题标题】:Fail to change the legend title and label with ggplot2 in R无法在 R 中使用 ggplot2 更改图例标题和标签
【发布时间】:2021-01-02 17:42:30
【问题描述】:

我试图将图例标题从 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"))

【问题讨论】:

    标签: r ggplot2 label legend


    【解决方案1】:

    在代码的最后部分试试这个。您可以学到的一课是填充和颜色是不同的美学。所以,如果你设置颜色,你必须使用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)))
    

    【讨论】:

    • 感谢您的帮助和第二个代码。真的很感激。
    【解决方案2】:

    你应该使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 2017-06-23
      • 2013-02-03
      • 2016-02-05
      • 2015-09-20
      相关资源
      最近更新 更多