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

非 Y 不嫁゛ 提交于 2019-12-25 03:15:48

问题


I'm (re)learning ggplot2 and trying to get this particular plot, which is proving quite evasive.

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

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:

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:

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

回答1:


Ok, it was simpler that I thought, I just needed to add stat = "identity" on the geom_bar call:

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



来源:https://stackoverflow.com/questions/29262916/how-i-get-a-facet-grid-plot-with-free-scales-and-barplots-with-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!