如何在ggplot中重命名图例? aes给出长度错误

How to rename figure legend in ggplot? aes gives length error

我是 R 的新手,运行 遇到了问题。

我使用 geom_point 绘制了散点图。

我已经成功地重命名了小平面网格标签,但我不知道如何重命名图形图例。我尝试将行 geom_point(aes(colour = Diet)) 重命名为 geom_point(aes(colour = diet_names)) 但出现以下错误:

Error: Aesthetics must be either length 1 or the same as the data (23): colour.

如果我删除除了下面的一个值之外的所有值(例如,只留下 fish_or = "Fish"),则不会发生错误,但显然我不想要一个有颜色的值在 table 上。

    diet_names <- c(
      fish_or = "Fish" ,
      fruit_pu = "Fruit" ,
      insects_nectar_bl = "Insects & Nectar" ,
      insects_re = "Insects" ,
      seeds_gr = "Seeds")

我想将图例编辑成更清晰的内容,因为它是我正在制作的海报的数据。谢谢:)

完整代码:

library(ggplot2)
library(dplyr)
Birdbeaks <- read.csv("Birdbeaks.csv", stringsAsFactors = FALSE)

diet_names <- c(
fish_or = "Fish" ,
fruit_pu = "Fruit" ,
insects_nectar_bl = "Insects & Nectar" ,
insects_re = "Insects" ,
seeds_gr = "Seeds") 

ggplot(Birdbeaks, aes(bill_lengthavg, bill_depthavg)) +
geom_point(aes(colour = diet)) +
labs(x = "Bill Length(cm)", y = "Bill Depth(cm)", colour = "Diet")+ 
guides(col = guide_legend(override.aes = list(shape = 15, size = 5))) +
theme_update()+
facet_grid(~diet, scales="fixed", labeller = as_labeller(diet_names))

希望有用

library(magrittr)
library(dplyr)
library(ggplot2)

    Birdbeaks %>%
      mutate(diet = case_when(
        diet == "fish_or" ~ "Fish",
        diet == "fruit_pu" ~ "Fruit",
        diet == "insects_nectar_bl" ~ "Insects & Nectar",
        diet == "insects_re" ~ "Insects",
        diet == "seeds_gr" ~ "Seeds"
      )) %>%
      ggplot(aes(bill_lengthavg, bill_depthavg)) +
        geom_point(aes(colour = diet)) +
        labs(x = "Bill Length(cm)", y = "Bill Depth(cm)", colour = "Diet") +
        guides(col = guide_legend(override.aes = list(shape = 15, size = 5))) +
        theme_update() +
        facet_grid(~diet, scales = "fixed")