更改图例中的顺序或图中的顺序,但不是两者

时间:2013-04-29 14:58:10

标签: r ggplot2

我有这些数据:

datat <- structure(list(Carga = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 
1L, 2L, 1L, 2L, 1L), .Label = c("Outra", "88"), class = "factor"), 
    Categoria = structure(c(1L, 1L, 3L, 3L, 2L, 2L, 1L, 1L, 3L, 
    3L, 2L, 2L), .Label = c("A", "G", "B"), class = "factor"), 
    Vagas = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
    2L, 2L), .Label = c("Ocupadas", "Autorizadas"), class = "factor"), 
    Cat.A.88 = c(26, 1, 30, 1, 18, 0, 57, 0, 39, 0, 0, 0)), .Names = c("Carga", 
"Categoria", "Vagas", "Cat.A.88"), class = "data.frame", row.names = c(NA, 
-12L))

和这个情节:

ggplot(datat, aes(x=Carga, y=Cat.A.88, fill=Vagas)) + geom_bar(stat='identity', position='dodge') + ylab('Vagas') + xlab('Carga horária') + facet_grid(. ~ Categoria) + coord_flip() 

如果与绘图颜色相比,图例颜色的顺序相反(绘图在红色前为绿色,图例在绿色前为红色)。我希望他们以相同的顺序出现。我尝试在order=-as.numeric(Vagas)中添加参数aes(),但没有改变任何内容。

1 个答案:

答案 0 :(得分:1)

这应该有所帮助:

ggplot(datat, aes(x=Carga, y=Cat.A.88, fill=Vagas)) + 
  geom_bar(stat='identity', position='dodge') + ylab('Vagas') + 
  xlab('Carga horária') + facet_grid(. ~ Categoria) + coord_flip() + 
  guides(fill = guide_legend(reverse=T))