ggplot2 multiline title, different indentations

前端 未结 5 722
失恋的感觉
失恋的感觉 2021-01-01 00:25

I am generating graphs for a publication and I\'d like to be able to label the panels of a figure in ggplot itself (as opposed to exporting to publisher, etc) so that they j

5条回答
  •  忘掉有多难
    2021-01-01 01:17

    You can do this by manipulating Grobs. Using gtable and grid on top of ggplot2.

    library("ggplot2")
    library("gtable")
    library("grid")
    
    p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, shape = Species))+
      geom_jitter(size = 6.5)+
      ggtitle("The Actual Long, Normal Title of Titliness")+
      theme(plot.title = element_text(hjust = 0.5, face = "bold", size = 30),
            axis.ticks = element_blank(),
            legend.text = element_text(size = 25),
            axis.title = element_text(size = 25, face = "bold"),
            axis.text = element_text(size = 25, vjust = 0.05),
            legend.position = "bottom",
            plot.margin = unit(c(4, 1, 1, 4), "lines"))  # We need bigger top/left margins to show the letter
    
    gt <- ggplot_gtable(ggplot_build(p))  # Building a gtable from the ggplot object
    # Adding the textGrob for the panel letter
    panel_letter = textGrob("A", x = 0.5, y = .9, 
                            just = c("left", "top"), 
                            gp = gpar(fontsize = 40, col =  "black", face="bold"))
    gt <- gtable_add_grob(gt, panel_letter, t=1, l=1, r=1)  # Append the Grob to the table
    
    p <- grid.draw(gt)  # Display the plot
    ggsave("plot.png",gt, width=10, height=10)  # If you want to save it.
    

提交回复
热议问题