JSP*_*JSP 5 plot themes r ggplot2
我想绘制一个随机主题的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
Run Code Online (Sandbox Code Playgroud)
问题:如何随机选择ggtheme?
Spa*_*man 11
来自函数的示例而不是函数的名称.此外,样本在从比标量更复杂的任何内容进行采样时返回一个列表,因此您需要第一个列表元素.例如:
> sample(c(sqrt, sqrt),2)
[[1]]
function (x) .Primitive("sqrt")
[[2]]
function (x) .Primitive("sqrt")
Run Code Online (Sandbox Code Playgroud)
所以得到一个随机主题函数:
random_theme <- sample(c(theme_gray, theme_bw, theme_light, theme_dark, theme_minimal, theme_classic), 1)[[1]]
Run Code Online (Sandbox Code Playgroud)
在你绘图时调用它:
ggplot(df, aes(x, y)) +geom_line() + random_theme()
Run Code Online (Sandbox Code Playgroud)
random_theme重新采样并重新绘制以进行更新.
此外,你可能不需要<<-我想的是一个宿醉,拼命想让一些东西工作......
你可以这样做match.fun():
random_theme = match.fun(sample(c("theme_gray", "theme_bw", "theme_light", "theme_dark", "theme_minimal", "theme_classic"), 1))
ggplot(df, aes(x, y)) +
geom_line() +
random_theme()
Run Code Online (Sandbox Code Playgroud)
由于您random_theme是一个character向量,因此您可以使用eval然后parse来解析您的主题。
library(tidyverse)
ggplot(df, aes(x, y)) +
geom_line() +
eval(parse(text = paste0(random_theme, "()")))
Run Code Online (Sandbox Code Playgroud)
或者更直接地说:
ggplot(df, aes(x, y)) +
geom_line() +
eval(parse(text = paste0(sample(c("theme_gray",
"theme_bw",
"theme_light",
"theme_dark",
"theme_minimal",
"theme_classic"), 1) , "()")))
Run Code Online (Sandbox Code Playgroud)