改变ggplot填充

时间:2018-05-09 18:04:46

标签: r ggplot2

我目前有以下代码可视化我的数据:

LIMIT 2

生成的条形图如下所示:

enter image description here

如何使最左边的三个条形成一种颜色(例如红色),中间三条形成另一种颜色(例如绿色),最右边三条形成另一种颜色(例如蓝色)。换句话说,三个连续的红色条,三个连续的绿色条和三个连续的蓝色条。

1 个答案:

答案 0 :(得分:2)

如果您将填充设置为FactorLevel,并使用“group”美学来控制子组栏的位置,则可以达到您想要的效果:

df <- data.frame(factor=rep("myFactor",9), filter=rep("Property Price", 9), outcome=rep("Price",9), filter.value = c(rep("Country X", 3), rep("Country Y", 3), rep("Country Z", 3)), FactorLevel=rep(c("Bungalow", "House", "Apartment"), 3), Outcome_Variable=rep("Price",9), mean=rep(20,9), min=rep(0,9), max=rep(100,9), sd=rep(5,9), n = rep(50,9), SE=rep(3,9))

attach(df)

print.plot <- function (rows) {
  ggplot(rows,aes(x=FactorLevel,y=mean,fill=FactorLevel))+
    geom_bar(stat="identity", position=position_dodge(), aes(group = filter.value), color = 'white')+
    geom_errorbar(aes(ymin = mean - SE, ymax = mean + SE, group = filter.value),position=position_dodge(.8), 
                  width = 0.25)+
    geom_text(aes(label=n, group = filter.value), vjust=1.6, color="black", position=position_dodge(.9), size=3.5)

}
print.plot(df)

enter image description here