How I get a facet_grid plot, with free scales AND

2019-09-19 05:13发布

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:

enter image description here

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条回答
疯言疯语
2楼-- · 2019-09-19 05:45

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")

Colors are still not quite good, but that's easier to fix, I hope...

查看更多
登录 后发表回答