【问题标题】:geom_vline, legend and performancegeom_vline,图例和性能
【发布时间】:2019-07-21 03:14:33
【问题描述】:

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

看完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))

这很好用:

但是很慢:

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))

图例不显示:

但它要快得多:

utilisateur     système      écoulé 
      1.193       0.270       1.496 

我怎样才能两全其美,即传奇,快速显示?

【问题讨论】:

    标签: r ggplot2 geom-vline


    【解决方案1】:

    您可以使用第一种方法,但将空的 data.frame 作为 data 参数传递给 geom_vline。速度问题是由geom_vlinemy.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 
    

    【讨论】:

    • 正是这样的问题让我怀疑 ggplot 的架构是否存在深深的误导。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2015-07-10
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多