【问题标题】:R how to add text (with mtext?) when plotting with the multiplot function from cookbook-rR在使用cookbook-r中的multiplot函数绘图时如何添加文本(使用mtext?)
【发布时间】:2015-03-11 08:18:14
【问题描述】:

我使用here 中的multiplot 函数将graph<-ggplot(...) 形式的大量图表与线堆叠在一起

png(filename = "qwerty.png", width = 1024, height = 1024, units = "px", 
    pointsize = 11, bg = "white",  res = 150)
multiplot(graph1,graph2,...., layout=matrix(c(1,2,3,4,5,6,7,8), nrow=8, 
          byrow=TRUE))
dev.off()

我想在第一个图表上方添加几行文本,例如,文本可能会进行复杂的编辑,例如某些字母的粗体。

我尝试使用,在multiplot前后放置它

mtext(expression(paste("only ", bold("a"), " should be bold")), 1, 1)

但我得到了错误

Error in mtext(expression(paste("only ", bold("a"), " should be bold")),  : 
  plot.new has not been called yet`

用我的文本''as the graph'' 叠加另一个空图会更好吗?如果是这样,我该怎么做?

这些数据可用于构建图表

p1 <- ggplot((subset(mtcars, gear==4)), aes(x=mpg, y=hp)) + 
      geom_point() +
      ggtitle("4 gears")
p2<-ggplot((subset(mtcars, gear==3)), aes(x=mpg, y=hp)) +
    geom_point() +
    ggtitle("3 gears")
multiplot(p1, p2, cols=2)

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    您可以使用 grid.arrange 代替 multiplot:

    library(gridExtra)
    
    grid.arrange(arrangeGrob(p1,p2,ncol=2, nrow=1), main = "Here your title should be inserted",nrow=1)
    

    如果您想调整一些文本参数,以下可能会有所帮助:

    grid.arrange(arrangeGrob(p1,p2,ncol=2, nrow=1), main = textGrob("Here your title should be inserted",gp=gpar(fontsize=16, font=2)))
    

    保存文件:

    png("example-plot.png")
    grid.arrange(arrangeGrob(p1,p2,ncol=2, nrow=1), main = textGrob("Here your title should be inserted",gp=gpar(fontsize=16, font=2)))
    dev.off()
    

    【讨论】:

    • 这确实有效,但我无法将堆叠的图保存在 png 文件中,因为显然,我必须先执行 g &lt;- arrangeGrob(p1, p2,ncol=2, nrow=1) 然后执行 ggsave(file="whatever.png", g, width = 22, height = 22, units = "in", dpi = 120) + dev.off() 并且我丢失了由 main = '''my text' 添加的文本。
    • 不确定你的文字为什么会消失,我在答案中做了一些更新,你应该得到包括标题的图片。
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2012-09-11
    • 2014-07-10
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多