使用ggplot2在循环中创建图

使用ggplot2在循环中创建图

本文介绍了使用ggplot2在循环中创建图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的示例数据集:



<$ p $ (名称= c(john,alex,mike,dennis,alex),
费用= c( 10,12,15,8,2),
type = c(食物,租金,租金,食物,食物)) b $ b

我想要在单个图表中为每个名称的费用绘制条形图。 alex的情节将如下所示:

  selected.name<  - alex
df1< - 子集(df,name == selected.name)
ggplot(data = df1,aes(type,expenses))+ geom_bar()

现在我想要使用一个循环,为df中的每个名称绘制相同的绘图。我试图使用运行上面剧情代码的for循环作为源文件。但我无法将名称变量传递给源文件,以便为每个名称绘制图形。现在我只能从for循环中获得一个图表。

解决方案

回答你的原始问题。使用标准R来做到这一点:

  doPlot = function(sel_name){
dum = subset(df,name = = sel_name)
ggobj = ggplot(data = dum,aes(type,expenses))+ geom_bar()
print(ggobj)
ggsave(sprintf(%s.pdf,sel_name ))
}
lapply(unique(df $ name),doPlot)

通过这种方式,最终得到大量名为Adam.pdf的pdf文件。然后,您可以使用pdftk(pdf工具包)将文件一起捕获到一个文档中。我仍然更喜欢使用例如更好的解决方案。小平面或不同类型的情节。

使用facetting不会更好吗?给出你的例子,代码将是:

pre $ g $ pggplot(data = df,aes(type,expenses))+
geom_bar()+ facet_wrap(〜name)

导致下面的情节:





也许对于250个名称和更多变量,这可能是一个问题。但是我仍然会考虑面向。

I have to generate 250 plots with the same view.

My example data set:

df <- data.frame(name = c("john","alex","mike","dennis","alex"),
             expenses = c("10","12","15","8","2"),
             type = c("food","rent","rent","food","food"))

I would like bar plots with the expenses for every name in a single plot. The plot for "alex" will look like:

selected.name <- "alex"
df1 <- subset(df, name == selected.name)
ggplot(data = df1, aes(type, expenses)) + geom_bar()

Now I want to use a loop that plots the same plot for every name in the df. I have tried to use a for loop that runs the plot code above as a source file. But I can't pass the name variable to the source file so that it plots the graph for every name. Now I only get one graph out of the for loop.

解决方案

To answer your orignal question. To do this using standard R:

doPlot = function(sel_name) {
   dum = subset(df, name == sel_name)
   ggobj = ggplot(data = dum, aes(type, expenses)) + geom_bar()
   print(ggobj)
   ggsave(sprintf("%s.pdf", sel_name))
}
lapply(unique(df$name), doPlot)

In this way you end up with a large number of pdf files called Adam.pdf etc. You could then use pdftk (pdf tool kit) to cat the files together in one document. I would still prefer, a better solution using e.g. facetting or a different type of plot.

Wouldn't it be much better to use facetting? Given your example the code would be:

ggplot(data = df, aes(type, expenses)) +
   geom_bar() + facet_wrap(~name)

which leads to the following plot:

Maybe for 250 names and more variables, this might be a problem. But I'd look at facetting nonetheless.

这篇关于使用ggplot2在循环中创建图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 14:21