向ggplot图形添加文件名或其他注释 [英] Add filename or other annotation to ggplot figures

查看:147
本文介绍了向ggplot图形添加文件名或其他注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot制作大部分图形.这些可以是单个面板,也可以是多面的.为了更容易跟踪修订,我想在绘图的一角生成一个包含一些文本的小标签.

I use ggplot to make most of my graphics. These can be single panels, or faceted. To make it easier to track revisions, I would like to generate a small label in the corner of the plot that includes some text.

在伪代码中,我正在寻找这样的东西:

In pseudo code, I am looking for something like this:

# generate the initial plot
p <- ggplot()
# add the label
p + someAnnotationFunction(label = "Version 1.0", x = 1, y = 0, 
                           hjust = "right", vjust = "bottom" )
# print
print(p) 

或者:将我的标签绘制在图形的右下角,而不会弄乱现有的ggplot图形.

Or: plot my label nestled in the lower right corner of my figure without messing up the existing ggplot graphics.

到目前为止,我还没有找到解决方案的运气. 如果您感兴趣,此方法(非常有趣)将不起作用有完整的m x n构面表.使用gridExtra的方法容易使绘图混乱.那么,有没有人有办法在使用ggplot生成的绘图上的任意位置添加任意文本?

So far I'm not having any luck finding a solution. This (very interesting) method doesn't work if you have a full m x n table of facets. Methods using gridExtra tend to mess with the plots too much. So, does anyone have a way to add arbitrary text anywhere on a plot that was generated using ggplot?

推荐答案

以下是基于Baptiste的评论的使用gridExtra()的可行解决方案:

Here's a worked solution using gridExtra(), based on Baptiste's comment:

require("ggplot2")
require("gridExtra")

# set our working directory 
working.dir <- '/Users/aclifton/Documents/projects/Rcode' 
setwd(working.dir)

# create a data frame
df <- data.frame(x =runif(100, 1, 10),
                 y = runif(100, 1, 10))
#create a plot
p <- ggplot(data = df,
            aes(x = x,
                y = y)) +
  geom_point()

print(p)        

我们现在有了情节,诀窍是添加标签并使用ggsave()保存整个情节:

We now have our plot, and the trick is adding that label and saving the overall plot using ggsave():

# label to show
sub.label = textGrob("Some kind of label", 
               gp=gpar(fontsize=6),
               x = unit(1, "npc"),
               hjust = 1,
               vjust = 0)

ggsave(filename=file.path(working.dir,'DemoPlot.png'),
       plot = arrangeGrob(p,
                          sub = sub.label,
                          clip = FALSE),
       scale = 1,
       width = 6.5,
       height = 3.5, 
       units = c("in"),
       dpi = 300)

这给你的是:

这篇关于向ggplot图形添加文件名或其他注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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