在图外添加与y轴对应的表

时间:2019-06-18 00:45:00

标签: r ggplot2

我有一个大图,我想在与y轴相对应的右侧添加一个表格。

我尝试了网格排列,gtable,tableGrob,但均无济于事。(该表未与y轴标签并置)(原始数据有35行,有时超出了绘图区域)。

plt <- ggplot(aaaa, aes(col, seq, label = ltr, fill = fill_calc2)) +  
         geom_text(size = 2.5, family = "mono", 
                   colour=factor(aaaa$colr), fontface ="bold") + 
         theme_minimal() + 
         labs(x=NULL, y=NULL) + 
         theme(panel.grid.major=element_blank(),
               panel.grid.minor=element_blank(), 
               axis.text.y = element_text(size = 8, family = "mono",color ="black",hjust = 0),
               axis.text.x  = element_text(face= "bold", size = 5,color ="black"), 
               plot.margin = (unit(c(.5, .5, 2, .5), "cm")), 
               plot.background = element_rect(fill = "white"), 
               axis.ticks.x  = element_line(color = "black")) 
grid.arrange(plt, table, ncol = 2)

图和表应对齐(高度和标签必须匹配)。图的宽度应大于表的宽度。

谢谢!

1 个答案:

答案 0 :(得分:1)

制作所需的ggplot

plt <- ggplot(dat, aes(col, seq, label = ltr, fill = fill_calc2)) +  
  geom_text(size = 2.5, family = "mono", 
            colour=factor(dat$colr), fontface ="bold") + 
  theme_minimal() + 
  labs(x=NULL, y=NULL) + 
  theme(panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(), 
        axis.text.y = element_text(size = 8, family = "mono",color ="black",hjust = 0),
        axis.text.x  = element_text(face= "bold", size = 5,color ="black"), 
        plot.margin = (unit(c(.5, .5, 2, .5), "cm")), 
        plot.background = element_rect(fill = "white"), 
        axis.ticks.x  = element_line(color = "black")) 

调整表格主题

核心:表格中的文字 colhead:在colname中输入文字 rowhead:行前的文字

adjustTheme <- ttheme_default(
  core = list(fg_params=list(cex = 0.8)),
  colhead = list(fg_params=list(cex = 0.7)),
  rowhead = list(fg_params=list(cex = 0.7)))

plt2 <- ggplot()+
  theme_minimal() + annotation_custom(tableGrob(table,theme= adjustTheme))

组成网格

grid.arrange(arrangeGrob(plt, plt2, ncol = 2,widths = c(4/5,1/5)))

enter image description here

已添加


adjustTheme <- ttheme_default(
  core = list(fg_params=list(cex = 0.8)),
  colhead = list(fg_params=list(cex = 0.7)),
  rowhead = list(fg_params=list(cex = 0.7)))

tableObject = tableGrob(table,theme= adjustTheme)
tableObject$widths[-1] <- rep(unit(1/2,"null"), 3)
tableObject$heights <- rep(unit(1/nrow(tableObject),"null"), nrow(tableObject))

grid.arrange(arrangeGrob(plt, tableObject, ncol = 2,widths = c(4/5,1/5)))

enter image description here