有没有一种方法可以自定义ggplot2主题中的刻度线?

时间:2019-12-23 19:20:29

标签: r ggplot2

您知道,ggplot2中有许多主题,例如theme_economist,theme_minimal,theme_tufte等。

例如,我想将此代码添加到可视化中:

theme_economist(axis.text.x = element_text(angle = 90))

但是我遇到了“未使用的参数”错误,因为我只能将此参数添加到主题函数中。

您可以简单地使用以下代码:

ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5) + theme_economist()

您有什么建议吗?

先谢谢了。

1 个答案:

答案 0 :(得分:1)

似乎您有两个选择。

选项1

创建一个新功能,将主题的元素添加到原始功能中,然后按ggplot()顺序使用该功能。在这里,theme_new是带有90度刻度标记的新主题。请注意,使用theme_new时会省略括号(即theme_new而不是theme_new())。

library(ggplot2)
library(ggthemes)

df <- data.frame(
    x = rnorm(1000, 500, 100),
    y = rnorm(1000, 500, 100)
)

theme_new <- theme_economist() + theme(
    axis.text.x = element_text(angle = 45)
)

ggplot(df, aes(x=x, y=y)) +
    geom_point() +
    theme_new

选项2:

通过复制theme_economist()库中的ggthemes定义来创建自己的主题,并将代码替换为所需的设计元素。如果要查看定义,可以查看here