Generating Multiple Plots in ggplot by Factor

流过昼夜 提交于 2019-12-17 18:39:35

问题


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.


回答1:


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() )
}


来源:https://stackoverflow.com/questions/31798162/generating-multiple-plots-in-ggplot-by-factor

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