如果其他情况在ggplot中添加一个额外的图层 [英] if else condition in ggplot to add an extra layer

查看:112
本文介绍了如果其他情况在ggplot中添加一个额外的图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想在ggplot中绘制两层,一个包含点,另一个包含行,如果满足某个标准的话。



没有标准的代码可能会显示像这样:

  library(ggplot2)

#按照年份总结电影评级数(电影,圆形(电影$评级),函数(df){
nums < - tapply(df $长度,df $年,长度)
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不等于表达式no value。

  tmp.data <-c(1,2,3 )#在这种情况下,条件满足

#尝试绘制包含两层的图层如果(tmp.data [1]!=no value){geom_point()+}
geom_line()
,则绘图函数中的条件为
p +
。 code>

失败....

 <$ c $如果(tmp.data [1]!=no value){geom_point()+}
p +


$ blockquote
geom_line()
geom_line:

stat_identity:

position_identity:(width = NULL,height = NULL)



解决方案

看到是一个语法错误。我能想到的最稳健的方式是:

$ p $ tmp.data< -c(1,2,3)$ b $如果(tmp.data [1]!=no value){
p = p + geom_point()
}
p + geom_line()

因此,您按顺序编写对象 p ,只添加 geom_point() if语句产生 TRUE


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.

这篇关于如果其他情况在ggplot中添加一个额外的图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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