如何添加具有不同大小和颜色的 ggplot2 字幕? [英] How to add a ggplot2 subtitle with different size and colour?

查看:21
本文介绍了如何添加具有不同大小和颜色的 ggplot2 字幕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using ggplot2 to improve precipitation barplots.

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

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

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 上使用猜测数字?有没有更好的方法来放置字幕(不仅仅是使用 ,而是使用不同文本颜色和大小的字幕)?

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 , but a subtitle with different text color and size)?

我需要能够与 ggsave 一起使用才能获得 pdf 文件.

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

这里有两个相关的问题:

Here are two related questions:

在绘图区域外添加脚注引用R?

如何在 R 中添加副标题并更改 ggplot 图的字体大小?

感谢您的帮助.

推荐答案

最新的 ggplot2 版本(即 2.1.0.9000 或更新版本)具有作为内置功能的字幕和绘图下方的标题.这意味着你可以这样做:

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

这篇关于如何添加具有不同大小和颜色的 ggplot2 字幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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