r - 随机选择ggtheme

标签 r ggplot2 plot themes

我想画一个随机主题的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/

相关文章:

R:如果未测试功能会抛出错误?

r - 部分斜体,axis.text.x

r - 当分解变量时,ggplot2 中的 Qplot 会导致多条回归线

r - 如何更改ggtern中长轴标题的位置?

r - 如何在 R 中以固定网格模式绘制 "matrix"

r - 更改 rmarkdown pdf 输出的背景颜色

r - 如何绘制等高线,显示 95% 的值落在 R 和 ggplot2 中的位置

r - 如何将 r 中多列的字符串数据折叠为一行?

r - 使用 ggplot2 facet wrap R 控制图表

r - 计算回归线与数据点之间的距离