【问题标题】:R adding word in the middle of grid arrangeR在网格排列中间添加单词
【发布时间】:2022-12-01 18:16:06
【问题描述】:

我正在写 R ggplot,我正在用 grid.arrange 安排多个图。

有没有办法在两个图之间添加一些词? 我希望输出像红色的字样。

谢谢您的帮助 :)

library(ggplot2)
library(gridExtra)
P1 <- ggplot(mtcars, aes(x = mpg)) +
  geom_histogram()
P2 <- ggplot(mtcars, aes(x = wt)) +
  geom_histogram()
grid.arrange(P1, *I want to add some information here*,P2, ncol = 1, nrow = 2)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用 grid 库中的 grid.text 函数,如下所示

    ### Libraries
    library(grid)
    library(ggplot2)
    library(gridExtra)
    
    ### Data
    data(cars)
    
    ### Initiating plots
    P1 <- ggplot(mtcars, aes(x = mpg)) +
      geom_histogram()
    
    P2 <- ggplot(mtcars, aes(x = wt)) +
      geom_histogram()
    
    ### Display plots
    grid.arrange(P1, P2, ncol = 1, nrow = 2)+
    grid.text("I want to add some information here", 
              x=unit(0.25, "npc"), 
              y=unit(.52, "npc"),
              gp=gpar(fontsize=20, col="red"))
    

    【讨论】:

      【解决方案2】:

      一种方法是创建另一个只有您想要的文本的ggplot,并在cowplot::plot_grid中使用它

      library(ggplot2)
      
      P1 <- ggplot(mtcars, aes(x = mpg)) + geom_histogram()
      
      P2 <- ggplot() + 
        annotate("text", x = 4, y = 25, size=8, 
                 label = "This is some text in the middle", color = "red") + 
        theme_void() 
      
      P3 <- ggplot(mtcars, aes(x = wt)) +  geom_histogram()
      
      cowplot::plot_grid(P1, P2, P3, rel_heights = c(1/2, 1/12, 1/2), 
                         align = "v", nrow = 3)
      

      【讨论】:

        猜你喜欢
        • 2021-07-22
        • 1970-01-01
        • 1970-01-01
        • 2018-05-29
        • 2023-03-11
        • 1970-01-01
        • 2019-12-02
        • 2011-12-18
        • 2018-08-01
        相关资源
        最近更新 更多