代码之家  ›  专栏  ›  技术社区  ›  Jeff238

为scale\u fill\u连续比例而不是离散比例制作图例

  •  -1
  • Jeff238  · 技术社区  · 2 年前

    scale_fill_gradientn() 这通常会产生一个连续的比例作为图例,但不知怎的,如果我使用下面附带的代码,结果会产生一个带有颜色框作为离散值的图例

      ggplot(aes(x=grouping,y=person,fill=score)) + 
      geom_tile(stat = "identity",position = "identity",colour="black",size=1) + 
      facet_grid(family~functional,switch = "y") +
      scale_fill_gradientn(colours = c("white","orange","red"),
        limits=c(0,100),breaks = c(0,50,100),labels=c("min","mid","max"),
        guide = guide_legend(direction = "horizontal",title.position = "bottom")) +
        labs(fill = "Average Percentage")
    

    enter image description here

    我注意到,只要我删除 guide 来自

    scale_fill_gradientn(colours = c("white","orange","red"),
        limits=c(0,100),breaks = c(0,50,100),labels=c("min","mid","max"))
    

    enter image description here

    但我的问题是,为什么会发生这种情况,如果我必须避免使用 指导

    1 回复  |  直到 2 年前
        1
  •  1
  •   jared_mamrot    2 年前

    下面是一个使用 palmer penguins dataset 作为一个 minimal, reproducible example

    library(tidyverse)
    library(palmerpenguins)
    
    penguins %>% 
      na.omit() %>%
      ggplot(aes(x = body_mass_g, y = bill_length_mm, fill = flipper_length_mm)) +
      geom_point(shape = 21, size = 3) +
      scale_fill_gradientn(colours = c("white", "orange", "red"),
                           limits = c(170, 240), breaks = c(180, 205, 235),
                           labels = c("min", "mid", "max"),
                           guide = guide_legend(direction = "horizontal",
                                                title.position = "bottom"))
    

    
    penguins %>% 
      na.omit() %>%
      ggplot(aes(x = body_mass_g, y = bill_length_mm, fill = flipper_length_mm)) +
      geom_point(shape = 21, size = 3) +
      scale_fill_gradientn(colours = c("white", "orange", "red"),
                           limits = c(170, 240), breaks = c(180, 205, 235),
                           labels = c("min", "mid", "max"),
                           guide = guide_colourbar(direction = "horizontal",
                                                   title.position = "bottom"))
    

    于2022年7月25日由 reprex package