gpt4 book ai didi

r - 随机选择ggtheme

转载 作者:行者123 更新时间:2023-12-04 16:11:21 25 4
gpt4 key购买 nike

我想画一个随机主题的ggplot(实际上,我想画很多图,每个图都有不同的主题)。考虑以下可重现的示例:

# Exmple data
df <- data.frame(x = 1:10, y = 1:10)

# Select theme randomly
random_theme <<- sample(c("theme_gray", "theme_bw", "theme_light", "theme_dark", "theme_minimal", "theme_classic"), 1)

# Draw ggplot
ggplot(df, aes(x, y)) +
geom_line() +
random_theme # This line does not work

问题:如何随机选择一个ggtheme?

最佳答案

从函数而不是函数名称中取样。此外,当从比标量更复杂的任何事物中采样时,sample 会返回一个列表,因此您需要第一个列表元素。例如:

> sample(c(sqrt, sqrt),2)
[[1]]
function (x) .Primitive("sqrt")

[[2]]
function (x) .Primitive("sqrt")

所以得到一个随机的主题函数:
random_theme <- sample(c(theme_gray, theme_bw, theme_light, theme_dark, theme_minimal, theme_classic), 1)[[1]]

并在绘图时调用它:
ggplot(df, aes(x, y)) +geom_line() + random_theme()

重新采样 random_theme并再次绘制更新​​。

此外,您可能不需要 <<-我想这是拼命尝试使某些东西起作用的宿醉......

关于r - 随机选择ggtheme,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479714/

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