if else 条件在 ggplot 添加一个额外的层 [英] if else condition in ggplot to add an extra layer
问题描述
假设我想在 ggplot 中绘制两个图层,一个包含点,另一个包含满足特定条件的线.
没有条件的代码可能如下所示:
library("ggplot2")# 按电影年份汇总电影评分数量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) # 在这种情况下条件满足# 尝试绘制两个图层,包括绘图函数中的条件p+if(tmp.data[1]!="no value"){ geom_point()+}geom_line()
失败....
错误:意外的}"在:"p+if(tmp.data[1]!="no value"){ geom_point()+}"
<块引用>
geom_line()geom_line:
stat_identity:
位置标识:(宽度= NULL,高度= NULL)
您看到的是语法错误.我能想到的最可靠的方法是:
tmp.data<-c(1,2,3)if(tmp.data[1]!="无值") {p = p + geom_point()}p + geom_line()
所以你将对象 p
组合成一个序列,只在 if 语句产生 TRUE
时添加 geom_point()
.
say I want to plot two layers in ggplot, one containing points and another one containing lines if a certain criteria is fulfilled.
The code without the criteria could look like this:
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()
now the condition for plotting the points and not only the lines would be, that an object called tmp.data does not equal the expression "no value".
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()
fails....
Error: unexpected '}' in:
"p+
if(tmp.data[1]!="no value"){ geom_point()+}"
geom_line() geom_line:
stat_identity:
position_identity: (width = NULL, height = NULL)
What you are seeing is a syntax error. The most robust way I can think of is:
tmp.data<-c(1,2,3)
if(tmp.data[1]!="no value") {
p = p + geom_point()
}
p + geom_line()
So you compose the object p
in a sequence, only adding geom_point()
when the if statements yields TRUE
.
这篇关于if else 条件在 ggplot 添加一个额外的层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!