我找到了一个很酷的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"))
我得到的情节是工作但没有颜色。有任何想法吗?
有几个问题需要解决。
正如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"))
OP要求从集合中删除NA。有两种选择:
ggplot()
删除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)
注意,这会产生一条警告消息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"))
这创建了完全相同的图表。
由于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