R 更改绘图填充

R 更改绘图填充,r,ggplot2,R,Ggplot2,我目前有以下代码来可视化我的数据: 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("Cou

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

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 = filter.value)) +
        geom_bar(stat = "identity", position = position_dodge()) +
        geom_errorbar(aes(ymin = mean - SE, ymax = mean + SE), position = position_dodge(.8), 
                      width = 0.25)+
        geom_text(aes(label = n), vjust = 1.6, color = "black", position = position_dodge(.9), size = 3.5)   
}

print.plot(df)

df如果将fill设置为
FactorLevel
,并使用“组”美学来控制子组栏的位置,则可以实现所需的效果:

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)

df为了使您的功能尽可能强大(尤其是最小化),无需使用
attach
-它在这里没有任何用处,这是一个不鼓励使用的习惯用法,没有理由将绘图放在函数中。这一点很好。我实际上需要绘制很多图,这就是为什么我把它做成一个函数。但是为了MCVE的目的,我应该删除该函数。