ggplot堆积条形图(比例)缩放到x变量

时间:2018-02-09 04:48:18

标签: r ggplot2

我需要创建一个相对比例的堆积条形图,缩放到x变量。这就是我的意思。

使用类似这样的数据框:

df <- data.frame(foo = rep(1:5,500), bar = as.factor(c(rep("a",100), rep("b",100), rep("c",100), rep("d",100), rep("e",100))), baz = c(rep("R", 5*250), rep("CRAN", 5*250)), val = rbinom(5*500,1,0.1))

我需要创建一个结合以下两个图的图。我需要第二个绘图的形状和第一个绘图的条形颜色编码(缩放到第二个绘图。理想情况下,我还会在其上绘制密度(如第一个绘图)。

library(ggplot2)
ggplot(subset(df, val == 1), aes(x = foo)) + geom_bar(aes(fill = bar), position = "fill") + scale_fill_brewer(type = "div", palette = 8, direction = 1) +  facet_wrap(~baz) + geom_density(aes(foo))
ggplot(subset(df, val == 1), aes(x = foo, y = as.factor(foo))) + geom_col(position = "identity") + scale_fill_brewer(type = "div", palette = 8, direction = 1) +  facet_wrap(~baz)

最终结果应该像左侧的小平面(在下图中)。 Gimped up geom_bar

我如何在ggplot2中执行此操作?

3 个答案:

答案 0 :(得分:1)

怎么样

 library(gridExtra)
 grid.arrange(p1, p2, ncol=1)

其中p1p2是两个ggplots。

p1 <- ggplot(subset(df, val == 1), aes(x = foo)) + geom_bar(aes(fill = bar), 
       position = "fill") + scale_fill_brewer(type = "div", palette = 8, 
       direction = 1) +  facet_wrap(~baz) + geom_density(aes(foo))

p2 <- ggplot(subset(df, val == 1), aes(x = foo, y = as.factor(foo))) + 
       geom_col(position = "identity") + scale_fill_brewer(type = "div", 
       palette = 8, direction = 1) +  facet_wrap(~baz)

答案 1 :(得分:1)

也许这样的事情可行:在geom_bar()添加stat = "identity"并删除fill = "position"。您可以用直方图(基本上是相同的密度)替换密度。

ggplot(subset(df, val == 1), aes(foo)) + 
    geom_bar(aes(y = foo, fill = bar), stat = "identity") + 
    geom_histogram(aes(foo), color = "black") +
    facet_wrap( ~ baz) +
    scale_fill_brewer(type = "div", palette = 8, direction = 1) +
    labs(x = NULL, y = NULL) +
    theme(legend.position = "bottom")

enter image description here

答案 2 :(得分:0)

这是我提出的解决方案:

df <- data.frame(foo = rep(1:5,500), bar = as.factor(c(rep("a",100), rep    ("b",100), rep("c",100), rep("d",100), rep("e",100))), baz = c(rep("R", 5*250), rep("CRAN", 5*250)), val = rbinom(5*500,1,0.1))

p <- ggplot(subset(df, val == 1), aes(x = foo)) + geom_bar(aes(fill = bar), position = "fill") + scale_fill_brewer(type = "div", palette = 8, direction = 1) +  facet_wrap(~baz)
p1 <- ggplot(subset(df, val == 1), aes(x = foo, y = as.factor(foo))) + geom_col(position = "identity") + scale_fill_brewer(type = "div", palette = 8, direction = 1) +  facet_wrap(~baz)

z <- ggplot_build(p)
z1 <-ggplot_build(p1)
z$data[[1]]$ymin <- z$data[[1]]$ymin*z$data[[1]]$x
z$data[[1]]$ymax <- z$data[[1]]$ymax*z$data[[1]]$x
z$data[[1]]$y <- z$data[[1]]$y*z$data[[1]]$x
z$layout$panel_ranges <- z1$layout$panel_ranges

plot(ggplot_gtable(z))

这就是它的样子:

Just what I was aiming for

这有效,但我可以接受其他(较少被黑客攻击)的解决方案。