r - 如何添加不同大小和颜色的 ggplot2 字幕?

标签 r ggplot2 subtitle

我正在使用 ggplot2 来改进降水条形图。

这是我想要实现的可重现示例:

library(ggplot2)
library(gridExtra)
secu <- seq(1, 16, by=2)
melt.d <- data.frame(y=secu, x=LETTERS[1:8])
m <- ggplot(melt.d, aes(x=x, y=y)) +
  geom_bar(fill="darkblue") + 
  labs(x="Weather    stations", y="Accumulated Rainfall [mm]") +
  opts(axis.text.x=theme_text(angle=-45, hjust=0, vjust=1),
       title=expression("Rainfall"), plot.margin = unit(c(1.5, 1, 1, 1), "cm"),
       plot.title = theme_text(size = 25, face = "bold", colour = "black", vjust = 5))
z <- arrangeGrob(m, sub = textGrob("Location", x = 0, hjust = -3.5, vjust = -33, gp = gpar(fontsize = 18, col = "gray40"))) #Or guessing x and y with just option
z

我不知道如何避免在 ggplot2 上的 hjust 和 vjust 上使用猜测数字?有没有更好的方式来放置字幕(不只是使用\n,而是具有不同文本颜色和大小的字幕)?

我需要能够与 ggsave 一起使用才能拥有 pdf 文件。

这里有两个相关的问题:

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?

感谢您的帮助。

最佳答案

最新的 ggplot2 版本(即 2.1.0.9000 或更新版本)将字幕和低于绘图的标题作为内置功能。这意味着您可以这样做:

library(ggplot2) # 2.1.0.9000+ 

secu <- seq(1, 16, by=2)
melt.d <- data.frame(y=secu, x=LETTERS[1:8])

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

关于r - 如何添加不同大小和颜色的 ggplot2 字幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156945/

相关文章:

r - 将多列相互相乘成R中的新数据框

多行时的ffmpeg字幕背景问题(使用.srt格式)

mpmovieplayercontroller - AVPlayer/MPMoviePlayerController 的字幕

video - 在 ffmpeg 中,如何使用 scale2ref 过滤器缩放 dvdsub 字幕以匹配视频大小?

r - 在 R 替代中使用变量

r - knitr:不同目录中的子文档

r - 从基础 R 图转换为 ggplot

r - 使用自定义渐变填充直方图箱

r - 如何在 R 中使用 WMS?

r - ggplot 和 geom_text()