代码之家  ›  专栏  ›  技术社区  ›  Ben

几何图形、图例和性能

  •  0
  • Ben  · 技术社区  · 7 年前

    我想在我的图上画几条垂直线,并为每条对应的线绘制一个图例。

    读完之后 this post ,以下是我实现的:

    set.seed(99)
    df.size <- 1e6
    my.df <- data.frame(dist = rnorm(df.size, mean = 0, sd = 2))
    library(ggplot2)
    ggplot(my.df, aes(x=dist)) + geom_histogram(binwidth = 0.5)
    
    vline1.threshold <- mean(my.df$dist)
    vline2.threshold <- mean(my.df$dist) + 3*sd(my.df$dist)
    

    现在来看情节:

    g <- ggplot(my.df, aes(x = dist)) +
      geom_histogram(binwidth = 0.5) +
      geom_vline(aes(color = "vline1", xintercept = vline1.threshold)) +
      geom_vline(aes(color = "vline2", xintercept = vline2.threshold)) +
      scale_color_manual("Threshold", values = c(vline1 = "red", vline2 = "blue"), labels = c("Mean", "Mean + 3*SD"))
    system.time(print(g))
    

    这很有效:

    enter image description here

    但速度非常慢:

    utilisateur     système      écoulé 
         51.667       1.883      53.652 
    

    (对不起,我的系统是法语的)

    然而,当我这样做时(使用aes之外的xintercept):

    g <- ggplot(my.df, aes(x = dist)) +
      geom_histogram(binwidth = 0.5) +
      geom_vline(aes(color = "vline1"), xintercept = vline1.threshold, color = "red") +
      geom_vline(aes(color = "vline2"), xintercept = vline2.threshold, color = "blue") +
      scale_color_manual("Threshold", values = c(vline1 = "red", vline2 = "blue"), labels = c("Mean", "Mean + 3*SD"))
    system.time(print(g))
    

    图例不显示:

    enter image description here

    但速度要快得多:

    utilisateur     système      écoulé 
          1.193       0.270       1.496 
    

    我怎样才能快速展示这两个世界中最好的一面,即一个传奇?

    0 回复  |  直到 7 年前
        1
  •  5
  •   pogibas    7 年前

    可以使用第一种方法,但传递空数据。框架 data 争论 geom_vline .速度问题是由 几何线 为中的每一行绘制线 my.df 具有 data = data.frame() 只策划过一次。

    g2 <- ggplot(my.df, aes(x = dist)) +
      geom_histogram(binwidth = 0.5) +
      # pass empty data.frame as data
      geom_vline(aes(color = "vline1", xintercept = vline1.threshold), data.frame()) +
      # pass empty data.frame as data
      geom_vline(aes(color = "vline2", xintercept = vline2.threshold), data.frame()) +
      scale_color_manual("Threshold", values = c(vline1 = "red", vline2 = "blue"), labels = c("Mean", "Mean + 3*SD"))
    
    # OPs solution
    # system.time(print(g))
    #   user  system elapsed 
    # 36.636   1.714  38.397 
    
    # data.frame() solution
    # system.time(print(g2))
    #   user  system elapsed 
    #  2.203   0.265   2.504 
    
    推荐文章