通过因子在ggplot中生成多个图 [英] Generating Multiple Plots in ggplot by Factor
问题描述
我有一个数据集,我想根据其中一列生成多个图。也就是说,我希望能够使用ggplot为每种因素制作一个单独的图。
以下是一些快速示例数据:
Variety = as.factor(c(a,b,a,b,a,b, (a),b,a,b)
Var1 = runif(10)
Var2 = runif(10)
mydata = as.data.frame(cbind( Var2,Var2))
我想通过Var2生成两个单独的Var1图,一个用于品种A,另一个用于品种B,最好是单一命令,但如果有办法在不拆分桌子的情况下做到这一点,那也可以。
您可以使用 facet_grid
或 facet_wrap
来按图表分割图表。$ $ p $ $ $ $ $ $ $ $ b $ g $
或者在不同的情节中,只需使用一个简单的循环
<$ (var in unique(mydata $ Variety)){
dev.new( )
print(ggplot(mydata [mydata $ Variety == var,],aes(Var1,Var2))+ geom_point())
}
pre>
I have a data set that I want to generate multiple plots for based on one of the columns. That is, I want to be able to use ggplot to make a separate plot for each variety of that factor.
Here's some quick sample data:
Variety = as.factor(c("a","b","a","b","a","b","a","b","a","b")
Var1 = runif(10)
Var2 = runif(10)
mydata = as.data.frame(cbind(Variety,Var1,Var2))
I'd like to generate two separate plots of Var1 over Var2, one for Variety A, a second for Variety B, preferably in a single command, but if there's a way to do it without splitting the table, that would be ok as well.
You can use facet_grid
or facet_wrap
to split up graphs by factors.
ggplot(mydata, aes(Var1, Var2)) + geom_point() + facet_grid(~ Variety)
or, on separate plots, just use a simple loop
for (var in unique(mydata$Variety)) {
dev.new()
print( ggplot(mydata[mydata$Variety==var,], aes(Var1, Var2)) + geom_point() )
}
这篇关于通过因子在ggplot中生成多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!