使用geom_bar为不同的facet_grids填充不同的填充

时间:2013-03-19 01:44:30

标签: r ggplot2 fill

我是ggplot2的新手,我有一个问题,我找不到答案。 我创建了以下玩具数据以帮助解释:

data <- data.frame(tech=c(rep(letters[1:15],2)), 
     sep=c(rep(c("SitutationA", "SitutationB"),each=15)), 
     error=c(runif(15,min=-0.2, max=0.5), runif(15, min=0.3, max=1)))

我想绘制一个geom_bar图表,显示每个技术“技术”(轴x)的“错误”(轴y),使用facet_grid分为两种不同的情况(SituationA和SituationB)。每个条形的颜色(fill)应代表每种技术的“误差”,而不是技术(作为一个因素)。情况A和B的误差以不同的比例测量。但是,在我的代码中,相同值的错误在两种情况下都具有相同的颜色。我不想要这种行为,因为它们是以不同的比例测量的。因此,我希望情况A和B中的颜色是独立的。

以下代码绘制图形,但在两种情况下使用相同的颜色。

ggplot(data, aes(x=tech, y=error)) +
  geom_bar(aes(fill=error), stat="identity", position="dodge") + 
  facet_grid(sep ~ ., scales="free_y") + 
  scale_fill_continuous(guide=FALSE)

我如何为每个方面使用不同的连续填充(situationA和situationB)?

谢谢。

1 个答案:

答案 0 :(得分:1)

在同一个地块上不能有两个不同的填充比例。

解决问题的方法可能是创建两个图,然后将它们与库grid.arrange()中的gridExtra放在一起。

在第一个图中只放置SitutationA的值。更改y比例以显示小数点后两位数的值(与第二个绘图相同)。删除了x轴标题,文本和刻度以及更改的绘图边距 - 将底部边距设置为-0.4以减少绘图之间的间距。

library(grid)
library(gridExtra)
p1<-ggplot(subset(data,sep=="SitutationA"), aes(x=tech, y=error)) +
  geom_bar(aes(fill=error), stat="identity", position="dodge") + 
  facet_grid(sep ~ ., scales="free_y") + 
  scale_fill_continuous(guide=FALSE)+
  scale_y_continuous(breaks=c(0,0.25,0.50))+
  theme(axis.text.x=element_blank(),
        axis.title.x=element_blank(),
        axis.ticks.x=element_blank(),
        plot.margin=unit(c(1,1,-0.4,1),"lines"))

对于第二个图(SitutationB),将顶部绘图边距更改为-0.4以减少绘图之间的间距。然后更改scale_fill_continuous()并提供了新颜色。

p2<-ggplot(subset(data,sep=="SitutationB"), aes(x=tech, y=error)) +
  geom_bar(aes(fill=error), stat="identity", position="dodge") + 
  facet_grid(sep ~ ., scales="free_y") + 
  scale_fill_continuous(guide=FALSE,low="red",high="purple") +
  theme(plot.margin=unit(c(-0.4,1,1,1),"lines"))

现在将两个地块放在一起。

grid.arrange(p1,p2)

enter image description here