相关疑难解决方法(0)

if else在ggplot中添加一个额外的图层

说我想在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()
Run Code Online (Sandbox Code Playgroud)

现在绘制点而不仅仅是线条的条件是,一个名为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()
Run Code Online (Sandbox Code Playgroud)

失败....

Error: unexpected '}' in:
"p+ 
if(tmp.data[1]!="no value"){ geom_point()+}"
Run Code Online (Sandbox Code Playgroud)

geom_line()geom_line: …

if-statement r ggplot2

34
推荐指数
4
解决办法
2万
查看次数

标签 统计

ggplot2 ×1

if-statement ×1

r ×1