简体   繁体   English

如何使用ggplot2获取带有自由刻度和条形图的facet_grid图?

[英]How I get a facet_grid plot, with free scales AND barplots, with ggplot2?

I'm (re)learning ggplot2 and trying to get this particular plot, which is proving quite evasive. 我正在(重新)学习ggplot2并尝试获取此特殊绘图,事实证明这很容易避免。

Earlier I found this question , which was useful, but not everything I need. 早些时候,我发现了这个问题该问题很有用,但并不是我需要的一切。 This is more or less what you get using the accepted answer to that Q: 这或多或少是您使用该问题的公认答案所获得的:

## Packages & data:
require(dplyr)
set.seed(0)
df <- data.frame(categ=c("A", "B", "C"), 
                 V1=rpois(3, 20), 
                 V2=rnorm(3, 100, 40), 
                 V2=runif(3)) %>% gather(Var, X, 2:4)
## Se below in "Example data" for how to get this example

p  <- ggplot(df, aes(categ, X, color=Var)) + geom_point()
p + facet_grid(Var ~ ., scale="free")

The resulting plot is this: 结果图是这样的:

在此处输入图片说明

However, I need to do the same, only with barplots instead of just points. 但是,我需要这样做,只用条形图而不是点数即可。 Anyone with some help? 有人需要帮助吗?

Thanks in advance, Juan 在此先感谢Juan

Example data 示例数据

Note that I used tidyr::ghather and magrittr 's pipe %>% to create my example, but the same can be achieved with reshape2::melt : 请注意,我使用了tidyr::ghathermagrittr的管道%>%来创建我的示例,但是使用reshape2::melt可以实现相同的效果:

require(reshape2)
set.seed(0)
df <- data.frame(categ=c("A", "B", "C"), 
                 V1=rpois(3, 20), 
                 V2=rnorm(3, 100, 40), 
                 V2=runif(3))
df <- melt(df, id="categ", variable.name="Var", value.name="X")

Anyway, the resultant data.frame looks like this: 无论如何,结果data.frame看起来像这样:

categ  Var           X
    A   V1  25.0000000
    B   V1  18.0000000
    C   V1  25.0000000
    A   V2 150.8971729
    B   V2 116.5856574
    C   V2  38.4019983
    A V2.1   0.1765568
    B V2.1   0.6870228
    C V2.1   0.3841037

Ok, it was simpler that I thought, I just needed to add stat = "identity" on the geom_bar call: 好的,我想起来更简单,我只需要在geom_bar调用上添加stat = "identity"

p  <- ggplot(df, aes(categ, X, color=Var)) + geom_bar(stat="identity")
p + facet_grid(Var ~ ., scale="free")

颜色仍然不太好,但是更容易修复,我希望...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM