尝试制作条形图,将每个分类列作为不同的颜色

问题描述 投票:-1回答:1

我找到了一个很酷的Wes Anderson调色板包,但我在这里实际上没有使用它。我正在查看的变量(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")) 

我得到的情节是工作但没有颜色。有任何想法吗?

r ggplot2 bar-chart
1个回答
1
投票

有几个问题需要解决。

Using the Wes Anderson palette

正如Mako已经提到的那样,在fill的召唤中缺少aes()美学。

此外,OP reports错误消息说Palette未找到。 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"

OP的代码中没有要求的调色板"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

Removing NA

OP要求从集合中删除NA。有两种选择:

  1. 告诉ggplot()删除NA。
  2. 通过过滤从te数据中删除NA。

在绘制x轴时,我们可以告诉ggplot()删除NA:

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

注意,这会产生一条警告消息Removed 3 rows包含非有限值(stat_count)。为了摆脱这个消息,我们可以使用geom_bar(na.rm = TRUE)

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

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"))

这创建了完全相同的图表。

Data

由于OP没有提供样本数据集,我们需要创建自己的:

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
© www.soinside.com 2019 - 2024. All rights reserved.