gpt4 book ai didi

r - 自定义ggtitle的背景颜色

转载 作者:行者123 更新时间:2023-12-01 23:29:17 24 4
gpt4 key购买 nike

我希望能够将 ggplot 的 ggtitle 的背景更改为 Forestgreen,同时保持文本为白色。颜色不应适用于整个图表,而应适用于标题。这是我到目前为止:

p <- ggplot(...)
p <- p + ggtitle("Market Updates") + labs(x = "Date", y = "High")
p <- p + theme(plot.title = element.text(hjust = 0.5, size = 20,
color = "#FFFFFF"))

我想让它看起来像这样:

enter image description here

最佳答案

从评论更新。

有几种方法可以做到这一点;使用 facet_ ,正如 Axeman 建议的那样,在绘图上方创建一个 strip (更改 strip 的格式比更改标题条更容易),或者您可以手动创建一个标题条,然后将其粘贴到绘图上。

例子

library(ggplot2)
library(gridExtra)
library(grid)

# Create dummy variable to facet on: this name will appear in the strip
mtcars$tempvar <- "Market Updates"

# Basic plot
# Manually added legend to match your expected result
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_line(aes(colour="Com")) +
scale_colour_manual(name="", values=c(Com = "#228b22") ) +
labs(x = "Date", y = "High")

使用 facet_ :这只会在绘图面板上添加颜色条,尽管标题居中。
p + facet_grid(. ~ tempvar) +
theme(strip.background = element_rect(fill="#228b22"),
strip.text = element_text(size=15, colour="white"))

其中产生

enter image description here

使用 grid功能:这会在绘图面板上添加颜色条,但标题位于图形窗口的中心。 (您可以通过将其添加到图 gtable 来获得更多的定位控制)
my_g <- grobTree(rectGrob(gp=gpar(fill="#228b22")),
textGrob("Market Updates", x=0.5, hjust=0.5,
gp=gpar(col="white", cex=1.5)))

grid.arrange(my_g, p, heights=c(1,9))

其中产生

enter image description here

关于r - 自定义ggtitle的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351011/

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