gpt4 book ai didi

用另一个默认主题中的元素替换一个 ggplot 默认主题元素

转载 作者:行者123 更新时间:2023-12-01 07:59:37 26 4
gpt4 key购买 nike

我真的很喜欢 ggplot2ggthemetheme_fivethirtyeight() 的一切,除了它隐藏了所有轴标题。

如何使用 theme_fivethirtyeight() 并告诉它从另一个主题继承轴标题规范?

最佳答案

这可以通过多种方式解决。最短的方法可能是按照@eipi10 的建议覆盖 element_text 参数。这需要对每个单独的地 block 重复。

另一种方法是根据现有主题创建您自己的自定义主题。 这种方法的好处是,一旦您完全按照自己喜欢的方式获得主题,就可以重复使用它。这是一个使用 theme_fivethiryeight() 的示例。

关键部分是:

   mytheme <- theme_fivethirtyeight() +
theme(axis.title = element_text(colour = "black" ))

创建一些要使用的虚拟数据:

library("ggplot2")
library("ggthemes")
# make the results reproducible
set.seed(5117)

start_date <- as.Date("2015-01-01")
end_date <- as.Date("2017-06-10")

# the by=7 makes it one observation per week (adjust as needed)
dates <- seq(from = start_date, to = end_date, by = 7)
val1 <- rnorm(length(dates), mean = 12.5, sd = 3)

qnt <- quantile(val1, c(.05, .25, .75, .95))

mock <- data.frame(myDate = dates, val1)

p <- ggplot(data = mock, mapping = aes(x = myDate, y = val1)) +
geom_line() +
geom_point() +
geom_hline(yintercept = qnt[1], colour = "red") +
geom_hline(yintercept = qnt[4], colour = "red") +
geom_hline(yintercept = qnt[2], colour = "lightgreen") +
geom_hline(yintercept = qnt[3], colour = "lightgreen") +
scale_x_date(date_breaks = "6 month", date_labels = "%b-%y") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))

这里加上原来的theme_fivethirtyeight()供引用:

p + theme_fivethirtyeight()

original theme plot

创建自定义主题:

mytheme <- theme_fivethirtyeight() +
theme(axis.title = element_text(colour = "black" ))

将自定义主题应用于原始情节:

p + mytheme

custom theme plot

您可以在命令提示符下键入主题名称(不带“()”)以了解还有哪些其他选项可用于自定义。在这里,我突出显示了被替换的 axis.title = element_blank():

theme_code

关于用另一个默认主题中的元素替换一个 ggplot 默认主题元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44073415/

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