gpt4 book ai didi

r - geom_vline、图例和性能

转载 作者:行者123 更新时间:2023-12-02 03:20:39 25 4
gpt4 key购买 nike

我想在我的绘图上绘制几条垂直线,并为每个相应的 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))

这效果很好:

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

如何才能两全其美,即快速显示图例?

最佳答案

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

关于r - geom_vline、图例和性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54904797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com