如何建立表格

时间:2018-10-26 23:55:39

标签: r

我想使用R创建一个表。我发现在[这里]有一个类似的问题:How can I add a table to my ggplot2 output?,但是最好的答案不能解决我的问题。

2 个答案:

答案 0 :(得分:3)

您可以按照注释的建议在单独的图表中绘制表格值,并使用plot_grid包中的cowplot来布置图表。

library(cowplot)
# assume the original plot was named p1

p2 <- ggplot(df, aes(x=avisit, y=forcats::fct_rev(Type), label = n)) + 
  geom_text(size = 3) +
  xlab("") +
  facet_grid(.~factor(visit)) +
  theme_void() +
  theme(axis.text.y = element_text(size = 10, margin = margin(r = 0)),
        panel.spacing = unit(0, "mm"),
        strip.text = element_blank())
# vary the size in geom_text / axis.text.y depending on your desired plot dimensions.

plot_grid(p1, p2, align = "v", axis = "lr",
          ncol = 1, rel_heights = c(1, 0.2))

plot

答案 1 :(得分:1)

在这里,您应该使用grid包通过将ggplot和表格放入两个堆叠的视口中来解决问题

#your code, use a variable p to hold the ggplot object
p <- ggplot(df, aes(x=avisit, y=mean, group=Type, color=Type, shape=Type)) + 
   scale_y_continuous(breaks=seq(0,18,2), limits=c(0, 18)) +
   geom_point(position=pd, cex=2) +
   xlab("") +
   ylab("Mean")  +
   scale_colour_manual(values=c("blue", "red")) +
   scale_shape_manual(values=c("triangle", "circle")) + 
   coord_cartesian(ylim = c(0, 18)) +
   facet_grid(.~factor(visit), scales = "free_x", space ="free_x",switch = "both") +
   theme_bw()  +
   theme(axis.text.y = element_text(margin = margin(r = 0)),  
         panel.spacing = unit(0, "mm"),                        
         strip.background = element_blank(),
         legend.title=element_blank(),
         strip.placement = "outside",
         legend.background = element_rect(color="black", fill="white", size=0.5, linetype="solid"), 
         legend.direction = "horizontal",
         panel.grid.minor = element_line(colour="white", linetype="dashed"),
         panel.grid.major = element_line(colour = "white",linetype="dashed"))

#--my code starts here--
#create a new blank viewport
grid.newpage()
#creating a viewport 5rows by 1col
pushViewport(viewport(layout = grid.layout(5, 1)))
#put the ggplot object into the first to fourth layout
print(p, vp = viewport(layout.pos.row = 1:4, layout.pos.col = 1))
grid.text(label = "TypeA  60      60      60      59      59      58      58      57      57      57      57      57", vp = viewport(layout.pos.row = 5, layout.pos.col = 1), x = unit(0.01, "npc"), y = unit(0.7, "npc"), just = "left", gp = gpar(fontsize = 10))
grid.text(label = "TypeB  59      59      59      58      58      58      58      57      57      56      56      56", vp = viewport(layout.pos.row = 5, layout.pos.col = 1), x = unit(0.01, "npc"), y = unit(0.45, "npc"), just = "left", gp = gpar(fontsize = 10))
grid.text(label = "No. of Subject", x = unit(0.01, "npc"), y = unit(0.9, "npc"), just = "left", gp = gpar(fontsize = 10), vp = viewport(layout.pos.row = 5, layout.pos.col = 1))