Customize background color of ggtitle

前端 未结 1 1403
抹茶落季
抹茶落季 2021-01-05 13:46

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

相关标签:
1条回答
  • 2021-01-05 14:24

    Update from comments.

    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.

    Example

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

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

    Which produces

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

    Which produces

    0 讨论(0)
提交回复
热议问题