【发布时间】:2014-05-19 20:50:27
【问题描述】:
假设我想在 ggplot 中绘制两层,如果满足特定条件,一层包含点,另一层包含线。
没有条件的代码可能如下所示:
library("ggplot2")
# Summarise number of movie ratings by year of movie
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
nums <- tapply(df$length, df$year, length)
data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)), number=as.vector(nums))
}))
p <- ggplot(mry, aes(x=year, y=number, group=rating))
p +
geom_point()+
geom_line()
现在绘制点而不仅仅是线条的条件是,名为 tmp.data 的对象不等于表达式“无值”。
tmp.data<-c(1,2,3) # in this case the condition is fulfilled
# attempt to plot the two layers including the condition in the plotting function
p+
if(tmp.data[1]!="no value"){ geom_point()+}
geom_line()
失败....
Error: unexpected '}' in:
"p+
if(tmp.data[1]!="no value"){ geom_point()+}"
geom_line() geom_line:
stat_identity:
position_identity: (width = NULL, height = NULL)
【问题讨论】:
-
为什么不直接改变顺序:
p + geom_line() + if(tmp.data[1]!="no value"){ geom_point()} -
@shadow。这仅在我的第二层是函数中的最后一个参数时才有效。如果我添加更多参数,例如:
+ theme(panel.background = element_rect(fill = "lightskyblue2"))它不再起作用
标签: r if-statement ggplot2