geom_hline 或 geom_vline 似乎不接受矢量作为参考线,如果在函数内部调用并且使用 facet_grid()

Posted

技术标签:

【中文标题】geom_hline 或 geom_vline 似乎不接受矢量作为参考线,如果在函数内部调用并且使用 facet_grid()【英文标题】:geom_hline or geom_vline does not seem to accept vector for reference line, if called inside a function and facet_grid() is used 【发布时间】:2017-10-14 04:21:25 【问题描述】:

如果我在自定义函数下调用 geom_hline 或 geom_vline 并且它从向量中获取值,我会遇到问题。在我在该函数 body.e.g 中添加 facet_grid() 之前,它似乎工作正常 无功能

c<- data.frame(A = c("carr","bike","truck","carr","truck","bike","bike","carr","truck","carr","truck","truck","carr","truck","truck"),
                B = c(10,20,30,23,45,56,78,44,10,20,30,10,20,30,67),
                D = c(1,2,3,1,2,3,2,3,2,3,2,2,3,2,1))
a = c(1:4)*4
ggplot(c, aes(A,B, color = D))+
  geom_point()+
  facet_grid( .~D)+
  geom_hline(yintercept = a,linetype = "dotted",size =0.3)

`

我明白了:

有功能

    tk_fun <- function(dat,x1,y1,clr)   # I need to have this a declared and defined with in function.  
 a = c(1:4)*4.5  p <- ggplot(dat, aes_string(colnames(dat)[1],colnames(dat)[2], color = colnames(dat)[3]))+
    geom_point()+    facet_grid( .~dat[,3])+
    geom_hline(yintercept = a,linetype = "dotted",size =0.3)  return(p)  tk_fun(c,"A","B","D")

使用函数我收到此错误:

$&lt;-.data.frame(*tmp*, "PANEL", value = c(1L, 2L, 3L, 1L, 中的错误: 替换有 15 行,数据有 4 我希望有人可以帮助我弄清楚,如何通过功能做到这一点,而不会出错。谢谢

【问题讨论】:

不要分配名称为 c 的对象。 c 是您在自己的代码中使用的基本基本函数。 【参考方案1】:

问题在于您对方面的定义。您需要使用正确的变量名称创建适当的公式调用,而不是直接使用数据。在这里使用pasteas.formula 可以提供帮助。

tk_fun <- function(dat,x1,y1,clr)   # I need to have this a declared and defined with in function.  
  a = c(1:4)*4.5  
  p <- ggplot(dat, aes_string(colnames(dat)[1],colnames(dat)[2], color = colnames(dat)[3]))+
    geom_point() +
    facet_grid(as.formula(paste('. ~', names(dat)[3]))) +
    geom_hline(yintercept = a, linetype = "dotted", size =0.3)  
  return(p) 

【讨论】:

以上是关于geom_hline 或 geom_vline 似乎不接受矢量作为参考线,如果在函数内部调用并且使用 facet_grid()的主要内容,如果未能解决你的问题,请参考以下文章

使用因式分解变量和 geom_hline / geom_vline 进行刻面

带有 `geom_vline` 和 `geom_hline` 的 ggplot。任务:需要单独的图例

数据为 POSIXct 时,ggplotly() 不显示 geom_vline / geom_hline

如何在同一个散点图上使用 geom_vline() 和 geom_hline 避免图例中的交叉效应?

R语言ggplot2可视化:为不同的分面图添加不同的geom_vline和geom_hline为不同的分组数据添加不同的横线竖线

geom_vline,图例和性能