【问题标题】:Syntax error in ggplot Function in RR中的ggplot函数中的语法错误
【发布时间】:2013-01-07 20:32:18
【问题描述】:

我想使用以下代码创建自动绘图功能:

plotTimeSeries <- list(temp1,temp2)

lapply(1:length(plotTimeSeries) , function(i) 
i$dt=strptime(i$dt, "%Y-%m-%d %H:%M:%S")
ggplot(i, aes(dt, ambtemp)) + geom_line() +
  scale_x_datetime(breaks = date_breaks("2 hour"),labels=date_format("%H:%M")) + xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Ambient Tempreture")+
  opts(title = ("Node i")))

但我遇到了以下错误:

Error: unexpected ')' in:
"           scale_x_datetime(breaks = date_breaks("2 hour"),labels=date_format("%H:%M")) + xlab("Time 00.00 ~ 24:00 (2007-09-29)") + ylab("Ambient Tempreture")+
           opts(title = ("Node i")))"

示例数据属性:

'data.frame':   731 obs. of  2 variables:
 $ ambtemp: num  0.23 0.26 0.35 0.31 0.32 0.3 0.36 0.33 0.27 0.27 ...
 $ dt     : POSIXct, format: "2007-09-29 23:39:05" "2007-09-29 23:41:05" "2007-09-29 23:43:05" ...

样本数据:

温度1:

 surtemp    date_time
1    0.23 2007-09-29 23:39:05
2    0.26 2007-09-29 23:41:05
3    0.35 2007-09-29 23:43:05
4    0.31 2007-09-29 23:45:05
5    0.32 2007-09-29 23:47:05
6    0.30 2007-09-29 23:49:05

温度2:

     surtemp    date_time
1   -1.42 2007-09-28 23:39:09
2   -1.24 2007-09-28 23:41:09
3   -1.28 2007-09-28 23:43:09
4   -1.28 2007-09-28 23:45:09
5   -1.24 2007-09-28 23:47:09
6   -1.42 2007-09-28 23:49:09

【问题讨论】:

  • 不,我不认为因为 ')' 而导致问题,因为它会回到 lapply(。如果我删除 opts ')',那么对应的 '(' 也应该被删除。之后删除两者我想出了其他错误。
  • 如果你希望两个表达式(设置i$dt和运行ggplot)都在函数体中执行,你需要在它们周围加上花括号{}
  • @BenBolker,我试过这样:plotTimeSeries
  • 不,大括号围绕着 函数 的主体。迭代语法调试令人沮丧。您能否发布一个可重现的示例 tinyurl.com/reproducible-000
  • 不可重现的例子是不可重现的。试着让它变得更简单更简单,最终你会遇到破坏它的一件事。

标签: r function plot ggplot2 syntax-error


【解决方案1】:

我认为恢复到for 循环会更容易混淆。试试:

plotTimeSeries <- list(temp1,temp2,temp3,temp4)
for (i in plotTimeSeries) {
   i$dt <- strptime(i$dt, "%Y-%m-%d %H:%M:%S")
   ggplot(i, aes(dt, ambtemp)) + geom_line() +
     scale_x_datetime(breaks = date_breaks("2 hour"),
                      labels=date_format("%H:%M")) + 
       labs(x="Time 00.00 ~ 24:00 (2007-09-29)",y="Ambient Temperature",
           title = (paste("Node",i)))
}

【讨论】:

  • 现在,我遇到了这个错误:'opts' 已被弃用。请改用“主题”。 (不推荐使用;最后在 0.9.1 版中使用)不推荐使用 opts(title="...") 设置绘图标题。请改用 labs(title="...") 或 ggtitle("...") 。 (已弃用;最后在 0.9.1 版中使用)“opts”已弃用。请改用“主题”。 (不推荐使用;最后在 0.9.1 版中使用)不推荐使用 opts(title="...") 设置绘图标题。请改用 labs(title="...") 或 ggtitle("...") 。 (已弃用;最后在 0.9.1 版本中使用)
  • 您是否尝试按照错误消息的建议从opts 切换到theme???(!)??? (我编辑了我的答案)
  • 但是通过使用主题我不能使用'i'。我想出了一个新错误:函数错误(el,elname):元素标题必须是元素文本对象。
  • 很抱歉,需要其他人来帮助您。如果没有可重现的示例,我无法继续这样做。祝你好运......
  • @Topdombili:这是一个 R-FAQ,在 for 循环中您需要 print ggplot 对象。
猜你喜欢
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多