Reputation: 2812
When using the default table output, the default is to plot the "axis" labels using the parameter names (k1 and k2 in this case). This is useful particularly for comparing cluster membership and the most important thing to denote is which cluster is rows and which is columns.
table(
k1=matrix(1:4, 2),
k2=matrix(1:4, 2)
)
k2
k1 1 2 3 4
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
4 0 0 0 1
I am trying to make use of tableGrob
to output some tables, composed with other ggplot components in grid.arrange
. However, the axis labels are lost.
grid.arrange(tableGrob(
table(
k1=matrix(1:4, 2),
k2=matrix(1:4, 2)
)
))
All I want to do is have those included or even include them manually after making the grob.
Thanks
Edit: Attempt with annotation_custom
:
Code:
ggTableAxis2 <- function(t) {
my_grob <- tableGrob(t)
my_plot <- ggplot(mapping = aes(k2, k1)) +
annotation_custom(my_grob) +
scale_x_continuous(position = 'top') +
theme(axis.title = element_text(angle = 0, hjust = 0),
axis.title.x.top = element_text(hjust = 0))
return(my_plot)
}
grid.arrange(
ggTableAxis2(
table(
k1=matrix(1:4, 2),
k2=matrix(1:4, 2)
)
),
ggTableAxis2(
table(
k1=matrix(1:4, 2),
k2=matrix(1:4, 2)
)
),
nrow=1
)
Upvotes: 2
Views: 1805
Reputation: 77096
not sure where exactly you want the labels, but it's probably easiest to add grobs to the gtable,
tbl <- table(
longlabel1=matrix(1:4, 2),
longlabel2=matrix(1:4, 2)
)
nms <- names(dimnames(tbl))
library(gridExtra)
library(grid)
library(gtable)
grid.newpage()
tg <- textGrob(nms[1], x=0, hjust=0)
lg <- textGrob(nms[2], x=1, hjust=1)
g <- tableGrob(tbl)
g <- gtable_add_rows(g, unit(1,"line"), 0)
g <- gtable_add_cols(g, grobWidth(lg), 0)
g <- gtable_add_grob(g, tg, t = 1, l=3, r=ncol(g))
g <- gtable_add_grob(g, lg, l = 1, t=2)
grid.draw(g)
Upvotes: 5
Reputation: 35187
You could use an empty ggplot
with mapped aesthetics:
library(grid)
library(gridExtra)
library(ggplot2)
my_grob <- tableGrob(table(k1 = matrix(1:4, 2), k2 = matrix(1:4, 2)))
my_plot <- ggplot(mapping = aes(k2, k1)) +
annotation_custom(my_grob) +
scale_x_continuous(position = 'top') +
theme(axis.title.y = element_text(angle = 0),
axis.title.x.top = element_text(hjust = 0))
grid.arrange(my_plot, my_plot, my_plot, my_plot)
Upvotes: 2