geom_vline,图例和性能

geom_vline, legend and performance

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

阅读后,这是我实现的:

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 

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

您可以使用第一种方法,但将空 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