由条形图按第四个变量着色

时间:2017-02-07 06:32:24

标签: r ggplot2 geom-bar

所以,我试图用ggplot2创建一个条形图,它将用第四个变量为图形填充着色。

 df = data.frame(c(1,1,2,2,3), c("A","B","C","D","E"),  c(1:5 / 4), c("Y", "N", "Y", "N", "N"))
 names(df)[1:4] <- paste("var", 1:4, sep = "")
 df$var1 <- as.factor(df$var1)
 df$var2 <- as.factor(df$var2)
 df$var4 <- as.factor(df$var4)
 ggplot(df, aes(x = var1, y = var3, fill = var2)) + facet_wrap(~var1, scale = "free") + 
    geom_bar(position = "dodge", colour = "black", stat = "identity") + 
    scale_fill_brewer(palette = "Set1") + scale_y_continuous(labels = scales::percent) 

我要做的是将条形图中显示的颜色设置为与var4对应,但仍然按var2对图表进行分析。我试图将aes(fill = var4)放入geom_bar部分,但这并没有给我我想要的结果。

我也遇到了相互堆叠的条形码的问题,这些条形似乎是基于var3作为字符或数字而改变的。要将其置于上下文中,var1将是一个问题ID,var2将是一个答案ID,var3将是一个百分比,var4将是答案是是否正确。

1 个答案:

答案 0 :(得分:0)

你想要这样的东西吗?

ggplot(df, aes(x = var2, y = var3, fill=var4)) + facet_wrap(~var1, scale = "free") + 
  geom_bar(position = "dodge", colour = "black", stat = "identity") + 
  scale_fill_brewer(palette = "Set1") + scale_y_continuous(labels = scales::percent) 

enter image description here