自定义ggtitle的背景色 [英] Customize background color of ggtitle

查看:134
本文介绍了自定义ggtitle的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to change the background of the ggtitle of my ggplot to forestgreen while keeping the text white. The color shouldn't apply to the whole of the graph but only the title. This is what I have so far:

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"))

我想使它看起来像这样:

I would like to make it look like this:

推荐答案

从评论更新.

有两种方法可以做到这一点;按照Axeman的建议,使用facet_在图上方创建条带(更改条带的格式比标题条更容易),或者您可以手动创建标题条,然后将其粘贴到图上.

There are a couple of approaches to do this; using facet_, as Axeman suggests, to create a strip above the plot (it is easier to change the the format of the strip than the title strip) , or you can create a title strip manually and then glue it to the plot.

示例

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_:尽管标题居中,这只会在打印面板上添加颜色条.

Using facet_: this only adds the colour bar across the plot panel, although the title is centered.

p + facet_grid(. ~ tempvar) +
        theme(strip.background = element_rect(fill="#228b22"),
              strip.text = element_text(size=15, colour="white"))

哪个生产

使用grid功能:这将在打印面板上添加颜色条,但标题位于图形窗口的中心. (通过将其添加到图gtable中,您可以对定位进行更多控制)

Using grid functions: this adds the colour bar across the plot panel, but the title is centered on the graphics window. (you could get a bit more control with positioning by adding it to the plot 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))

哪个生产

这篇关于自定义ggtitle的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆