代码之家  ›  专栏  ›  技术社区  ›  JD Long

向现有图形添加ggplot2 stat_函数

  •  5
  • JD Long  · 技术社区  · 6 年前

    我有一个图,我想在图上叠加一个函数形式。似乎是直截了当,但我错过了什么。这是我使用的示例数据和说明 stat_function 尝试添加 f1 到图表:

    library(ggplot2)
    sample_data <- data.frame(rate  = c(0.514492753623188, 0.553072625698324, 0.656527249683143, 0.675694939415538,
                                        0.68681076312307, 0.715657311669128, 0.792349726775956), 
                              level = c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85) )
    
    f1 <- function(x) pbeta(x, shape1=1.01, shape2=.9 ) * 100
    
    g <- ggplot() +
      geom_line(aes(y = rate*100 , x = level), 
                data = sample_data, stat="identity") +
      stat_function(fun = f1) 
    g
    

    如你所见, F1 线不在那里。

    作为一种替代方法,我可以将这些点添加到初始data.frame中,然后用 geom_line 如以下示例所示:

    ## add f1 to data.frame
    sample_data$f1 <- f1(sample_data$level )
    
    g <- ggplot() +
      geom_line(aes(y = rate*100 , x = level), 
                data = sample_data, stat="identity") +
      geom_line(aes(y = f1 , x = level), 
       data = sample_data, stat="identity", color='red')
    g
    

    这样就行了,我能得到我需要的,但我不明白为什么 统计功能 没用。有什么建议吗?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Tung    6 年前

    你需要 data = sample_data, aes(y = rate*100 , x = level) 在你的第一个 ggplot 呼叫SO stat_function 了解正在使用的数据

    library(ggplot2)
    
    sample_data <- data.frame(rate  = c(0.514492753623188, 0.553072625698324, 0.656527249683143, 0.675694939415538,
                                        0.68681076312307, 0.715657311669128, 0.792349726775956), 
                              level = c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85) )
    
    f1 <- function(x) pbeta(x, shape1=1.01, shape2=.9 ) * 100
    
    g <- ggplot(data = sample_data, aes(y = rate*100 , x = level)) +
      geom_line() +
      stat_function(fun = f1, color = "red")
    g
    

    创建于2018-05-20 reprex package (v0.2.0版)。