带有geom_bar和facet_wrap的ggplot未显示分组堆积条形图的图例

时间:2018-10-09 23:15:34

标签: r ggplot2

我正在尝试创建一个分组的堆叠条形图面板,但是以下“年龄”的图例不会自动显示。如何显式添加此图例?

library(ggplot2)

# create the dataset
species=c(rep("A" , 2) , rep("B" , 2))
strain=rep(c("i" , "ii" ),2)
age=rep(c(1,2,3,4),4)
count=abs(rnorm(16 , 0 , 15))
data=data.frame(species,strain,age,count)

ggplot(data,aes(x=strain,y=count,fill=age))+
  geom_bar(stat = "identity",size=0.5,col="black",fill=rep(c("black","saddlebrown","darkgreen","goldenrod"),times=4))+
  facet_wrap(~species)+
  labs(x="Species",y="Count")

2 个答案:

答案 0 :(得分:1)

因为您在fill=rep(c("black","saddlebrown","darkgreen","goldenrod"),times=4)之后的geom_bar()中指定了aes(fill = age)。您应该使用scale_fill_xxx手动指定所需的颜色。

library(dplyr)
library(ggplot2)

# create the dataset
set.seed(123)
species <- c(rep("A", 2), rep("B", 2))
strain <- rep(c("i", "ii"), 2)
age <- c(rep(c(1, 3, 4, 2), 1), rep(c(2, 4, 2, 3), 2), rep(c(3, 1, 3, 1), 1))
count <- abs(rnorm(16, 0, 15))
data <- data.frame(species, strain, age, count)

### convert age to factor
data <- data %>% 
  as_tibble() %>% 
  mutate(age = factor(age)) %>% 
  arrange(species, strain)
data
#> # A tibble: 16 x 4
#>    species strain age   count
#>    <fct>   <fct>  <fct> <dbl>
#>  1 A       i      1      8.41
#>  2 A       i      2      1.94
#>  3 A       i      2     10.3 
#>  4 A       i      3      6.01
#>  5 A       ii     3      3.45
#>  6 A       ii     4     25.7 
#>  7 A       ii     4      6.68
#>  8 A       ii     1      1.66
#>  9 B       i      4     23.4 
#> 10 B       i      2      6.91
#> 11 B       i      2     18.4 
#> 12 B       i      3      8.34
#> 13 B       ii     2      1.06
#> 14 B       ii     3     19.0 
#> 15 B       ii     3      5.40
#> 16 B       ii     1     26.8

ggplot(data, aes(x = strain, y = count, fill = age)) +
  geom_col(color = 'black') +
  facet_grid(~ species) +
  scale_fill_brewer(palette = 'Dark2') +
  labs(x = "Species", y = "Count") +
  theme_minimal(base_size = 14)

### user-defined color scheme
myColor <- c('#a6cee3','#1f78b4','#b2df8a','#33a02c')
ggplot(data, aes(x = strain, y = count, fill = age)) +
  geom_col(color = 'black') +
  facet_grid(~ species) +
  scale_fill_manual(values = myColor) +
  labs(x = "Species", y = "Count") +
  theme_minimal(base_size = 14)

reprex package(v0.2.1.9000)于2018-10-09创建

答案 1 :(得分:0)

好的,我想我已经在您的@Tung的帮助下得到了它

ggplot(data,aes(x=strain,y=count,fill=age))+
  geom_col() +
  geom_bar(stat = "identity",size=0.5,col="black",fill=rep(c("black","saddlebrown","darkgreen","goldenrod"),times=4))+
  facet_wrap(~species)+
  labs(x="Species",y="Count")+
  theme(legend.position = "right") +
  theme(axis.title.y = element_text(margin = margin(r = 20)))+
  scale_fill_manual(values = c("black","saddlebrown","darkgreen","goldenrod"))

enter image description here