代码之家  ›  专栏  ›  技术社区  ›  John Thomas

尝试用不同颜色的分类列制作条形图

  •  -1
  • John Thomas  · 技术社区  · 8 年前

    我发现了一个很酷的维斯安德森调色板包,但我在这里失败,在实际使用它。我看到的变量(Q1)有选项1和2。有一个NA的集合,这是正在绘制,但我想删除它以及。

    library(readxl)
    library(tidyverse)
    library(wesanderson)
    
    RA_Survey <- read_excel("file extension")
    
    ggplot(data = RA_Survey, mapping = aes(x = Q1)) +
      geom_bar() + scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest")) 
    

    我得到的情节是工作,但没有颜色。有什么想法吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Community Mohan Dere    6 年前

    有几个问题需要解决。

    如前所述 Mako fill 审美缺失的呼唤 aes() .

    此外,OP reports 一条错误消息 找不到调色板 . 这个 wesanderson 包包含可用选项板的列表:

    names(wesanderson::wes_palettes)
    
     [1] "BottleRocket1"  "BottleRocket2"  "Rushmore1"      "Rushmore"       "Royal1"         "Royal2"         "Zissou1"       
     [8] "Darjeeling1"    "Darjeeling2"    "Chevalier1"     "FantasticFox1"  "Moonrise1"      "Moonrise2"      "Moonrise3"     
    [15] "Cavalcanti1"    "GrandBudapest1" "GrandBudapest2" "IsleofDogs1"    "IsleofDogs2"
    

    没有名为 "GrandBudapest" 按照操作规程的要求。相反,我们必须在两者之间做出选择 "GrandBudapest1" "GrandBudapest2" .

    help("wes_palette")

    下面是一个工作示例,它使用 数据 以下部分:

    library(ggplot2)
    library(wesanderson)
    ggplot(RA_Survey, aes(x = Q1, fill = Q1)) +
      geom_bar() + 
      scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest1"))
    

    enter image description here

    1. 告诉 ggplot() 卸下NAs。
    2. 通过筛选从te数据中删除NAs。

    我们看得出来 ggplot() 要在打印x轴时删除NAs:

    library(ggplot2)
    library(wesanderson)
    ggplot(RA_Survey, aes(x = Q1, fill = Q1)) +
      geom_bar() + 
      scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest1")) +
      scale_x_discrete(na.translate = FALSE)
    

    enter image description here

    注意,这会产生一条警告消息 删除了3行包含非有限值(stat\u count)。 geom_bar(na.rm = TRUE) .

    另一个选项通过过滤从数据中删除NAs

    library(dplyr)
    library(ggplot2)
    library(wesanderson)
    ggplot(RA_Survey %>% filter(!is.na(Q1)), aes(x = Q1, fill = Q1)) +
      geom_bar() + 
      scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest1"))
    

    数据

    library(dplyr)
    set.seed(123L)
    RA_Survey <- data_frame(Q1 = sample(c("1", "2", NA), 20, TRUE, c(3, 6, 1)))
    RA_Survey
    
    # A tibble: 20 x 1
       Q1   
       <chr>
     1 2    
     2 1    
     3 2    
     4 1    
     5 NA   
     6 2    
     7 2    
     8 1    
     9 2    
    10 2    
    11 NA   
    12 2    
    13 1    
    14 2    
    15 2    
    16 1    
    17 2    
    18 2    
    19 2    
    20 NA
    
    推荐文章