在同一数据帧中自动生成ggplot [英] Automating producing ggplot in same dataframe

查看:52
本文介绍了在同一数据帧中自动生成ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,该数据集的第一列为日期格式的日期,然后为约50列.所有列均具有相同的比例并且是数字.我试图一次绘制两列,以周期为单位讲第1列和第2列,然后讲第3列和第4列,依此类推,直到用完迭代为止.

I have a dataset that has first column as periods in date format and then about 50 columns. All columns have the same scale and are numbers. I'm trying to plot two columns at a time lets say Column 1 and Column 2 by period and then Column 3 and Column 4 etc until I run out of iteration.

我编写的功能不起作用.它不会给我任何错误,但不会产生任何输出.当我在循环外运行代码时,它可以工作.

The function I wrote, won't work. It doesn't give me any error but produces no output. When I run the code outside of the loop it works.

以下可复制的样本

H<-data.frame(replicate(10,sample(0:20,10,rep=TRUE)))  
H$Date<-seq(as.Date('2001-03-31'),by='quarter',length=10)
H<-H[,c(11,1,2,3,4,5,6,7,8,9,10)]



 plotmebabe<-function(a){
  for (i in 2:length(a)){
    ggplot(data=a,aes(x=Date)) + 
      geom_line(aes(y=a[,i]),color="blue",size=2)+
      geom_line(aes(y=a[,i+1]),color="pink",size=2) +
      ylab(label="This is Y axis")+
      xlab("This is X axis")+
      ggtitle("Hello")+ 
      theme(plot.title = element_text(lineheight=.8, face="bold"))
  }}

推荐答案

仅通过ggplot对象绘制它实际上是print()-ed.当您在交互式命令行中键入内容时,结果将隐式打印()-ed.在for循环内运行代码时,不会发生这种隐式打印.您需要在对象上实际调用print()来触发图形.

A ggplot object is only drawn with it is actually print()-ed. When you type something at the interactive command line, the results are implicitly print()-ed. When you run code inside of for loop, this implicit printing doesn't happen. you need to actually call print() on the object to trigger the drawing.

这是更新版本(也修复了其他错误)

Here's an updated version (fixing other mistakes as well)

 plotmebabe<-function(a){       
  for (i in 2:(ncol(a)-1)){
    print(ggplot(data=a,aes(x=Date)) + 
      geom_line(aes_string(y=names(a)[i]),color="blue",size=2)+
      geom_line(aes_string(y=names(a)[i+1]),color="pink",size=2) +
      ylab(label="This is Y axis")+
      xlab("This is X axis")+
      ggtitle("Hello")+ 
      theme(plot.title = element_text(lineheight=.8, face="bold")))
  }}
plotmebabe(H)

这篇关于在同一数据帧中自动生成ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆