如何使用ggplot2获得带有自由刻度和条形图的facet_grid图?
我正在(重新)学习 ggplot2
并尝试获取此特殊代码情节,这被证明是非常回避的.
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")
结果图是这样的:
但是,我需要这样做,只用条形图而不是点数即可.有人需要帮助吗?
However, I need to do the same, only with barplots instead of just points. Anyone with some help?
预先感谢,胡安
请注意,我使用了 tidyr :: ghather
和 magrittr
的管道%>%
来创建我的例如,但是使用 reshape2 :: melt
:
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")
无论如何,生成的 data.frame
看起来像这样:
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
好吧,我想这很简单,我只需要在 geom_bar
呼叫:
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")