gpt4 book ai didi

R ggplot2 : change colour of font and background in facet strip?

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

我正在尝试自定义一个包含刻面的 ggplot2 图,并且想要更改刻面条的颜色以及字体的颜色。我找到了一些 code更改 strip.background颜色,但无法修改它以更改字体颜色......知道吗?

到目前为止我得到了什么:

library(ggplot2)
library(grid)

p <- ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(drv ~ cyl) +
ggtitle("How to change coloour of font in facet strip?")

g <- ggplot_gtable(ggplot_build(p))
strip_both <- which(grepl('strip-', g$layout$name))
fills <- c("red","green","blue","yellow","red","green","blue","yellow")
k <- 1

for (i in strip_both) {
j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- fills[k]
k <- k+1
}
grid.draw(g)



创建于 2018-11-23 由 reprex package (v0.2.1)

最佳答案

当然有人可以找到更好的解决方案,但到目前为止我只能做到这一点:

library(ggplot2)
library(grid)
library(RColorBrewer)

p <- ggplot(mpg, aes(x = displ, y = cty)) +
geom_point() +
facet_grid(drv ~ cyl) +
ggtitle("How to change coloour of font in facet strip?") +
ggthemes::theme_few()

g <- ggplot_gtable(ggplot_build(p))

strips <- which(grepl('strip-', g$layout$name))

pal <- brewer.pal(8, "Paired")


for (i in seq_along(strips)) {
k <- which(grepl('rect', g$grobs[[strips[i]]]$grobs[[1]]$childrenOrder))
l <- which(grepl('titleGrob', g$grobs[[strips[i]]]$grobs[[1]]$childrenOrder))
g$grobs[[strips[i]]]$grobs[[1]]$children[[k]]$gp$fill <- pal[i]
g$grobs[[strips[i]]]$grobs[[1]]$children[[l]]$children[[1]]$gp$col <- pal[i + 1]
}

plot(g)

change text and strips colors

关于R ggplot2 : change colour of font and background in facet strip?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53455092/

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