Tlopasha
Tlopasha

Reputation: 79

make ggplot panel-background like in gtable

I'm trying to make a graphic like this :

enter image description here

Optimal/efficient plotting of survival/regression analysis results

hier is my example code :

library(gtable)
library(grid)
library(gridExtra)
library(ggplot2)

tg <- tableGrob(iris[1:5,1:3], rows = NULL, cols=NULL)
tg$heights <- unit(rep(1,nrow(tg)), "null")

p <- qplot(1:5,1:5) + ggtitle("Title", subtitle = "another line") + 
theme_grey(12) +
scale_y_continuous(expand=c(0,0.5))
g <- ggplotGrob(p)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = 0)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = -1)
g <- gtable::gtable_add_grob(g, list(tg, tg), t = 6, l=c(1,ncol(g)), r=c(1,ncol(g)))
grid.newpage()
grid.draw(g)

enter image description here

Is that possible with ggplot and gtable to change the background color of the ggplot Panel and set the Zebra-style to it like the other two gtables to be similar to the first example ?.

thanks,

Upvotes: 3

Views: 868

Answers (1)

pogibas
pogibas

Reputation: 28329

As @MrFlick said you have to add some kind of geom layers in the background. This is my approach:
Create two data frames, one for points and one for segments and adjust segment size to match table rows.

tg <- tableGrob(iris[1:5,1:3], rows = NULL, cols=NULL)
tg$heights <- unit(rep(1,nrow(tg)), "null")
dSegment <- data.frame(X = 0, XE = 6, Y = 1:5, YE = 1:5)
dPoint <- data.frame(X = 1:5, Y = 1:5)

p <- ggplot() + 
    geom_segment(data = dSegment, 
                 aes(x = X, xend = XE, y = Y, yend = YE, color = factor(Y %% 2)),
                 size = 40) +
    geom_point(data = dPoint, aes(X, Y)) +
    ggtitle("Title", subtitle = "another line") + 
    scale_y_continuous(expand = c(0, 0.5)) +
    scale_x_continuous(breaks = c(1:5)) +
    scale_color_manual(values = c("#dbdbdb", "#e9e9e9")) +
    theme_grey(12) +
    theme(panel.grid.major = element_blank(), 
          panel.grid.minor = element_blank(),
          panel.background = element_blank(),
          legend.position = "none")
g <- ggplotGrob(p)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = 0)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = -1)
g <- gtable::gtable_add_grob(g, list(tg, tg), t = 6, l=c(1,ncol(g)), r=c(1,ncol(g)))
grid.newpage()
grid.draw(g)

enter image description here

Upvotes: 2

Related Questions