How to add a ggplot2 subtitle with different size and colour?

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

I'm using ggplot2 to improve precipitation barplots.

Here's a reproducible example of what I want to achieve:

library(ggplot2) library(gridExtra) secu 

I don't know how to avoid using guessing numbers on hjust and vjust on ggplot2? Is there a better way to put a subtitle (not just using \n, but a subtitle with different text color and size)?

I need to be able to use with ggsave to have a pdf file.

Here are two related questions:

Add a footnote citation outside of plot area in R?

How can I add a subtitle and change the font size of ggplot plots in R?

Thanks for any help.

回答1:

The latest ggplot2 builds (i.e., 2.1.0.9000 or newer) have subtitles and below-plot captions as built-in functionality. That means you can do this:

library(ggplot2) # 2.1.0.9000+   secu 


回答2:

Ignore this answer ggplot2 version 2.2.0 has title and subtitle functionality. See @hrbrmstr's answer below.


You could use nested atop functions inside an expression to get different sizes.

EDIT Updated code for ggplot2 0.9.3

m 



回答3:

It appears opts is deprecated as of ggplot 2 0.9.1 and no longer functional. This worked for me with the latest versions as of today: + ggtitle(expression(atop("Top line", atop(italic("2nd line"), "")))).



回答4:

This version uses a gtable function. It allows two lines of text in the title. The text, size, colour, and font face of each line can be set independently of the other. However, the function will modify a plot with a single plot panel only.

Minor edit: Updating to ggplot2 v2.0.0

# The original plot library(ggplot2)  secu 



回答5:

it's not too hard to add grobs to the gtable and make a fancy title that way,

library(ggplot2) library(grid) library(gridExtra) library(magrittr) library(gtable)  p %   gtable_add_rows(sum(tg$heights), 0) %>%   gtable_add_grob(grobs=tg, t = 1, l = 4)  %>%   grid.draw() 



回答6:

You could use wrap the plot in grid.arrange and pass a custom grid-based title,

library(ggplot2) library(gridExtra)  p 


回答7:

You might have noticed that Sandy's code doesn't produce a bold title for "Rainfall" - the instruction to make this bold should occur within the atop() function rather than the theme() function.

ggplot(melt.d, aes(x=x, y=y)) +   geom_bar(fill="darkblue", stat = "identity") +   labs(x="Weather    stations", y="Accumulated Rainfall [mm]") +   ggtitle(expression(atop(bold("Rainfall"), atop(italic("Location"), "")))) +  theme(axis.text.x = element_text(angle=-45, hjust=0, vjust=1),  plot.title = element_text(size = 25, colour = "black", vjust = -1)) 



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!