Created
September 19, 2018 14:45
-
-
Save SimonCoulombe/91eb398def87061897858106fcabc55c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#https://stackoverflow.com/questions/35536289/how-to-get-the-grid-of-2-graphs-with-different-geom-match-with-ggplot2 | |
library(ggplot2) | |
library(gridExtra) | |
library(dplyr) | |
library(tidyr) | |
pouet <-tibble(decile = seq(1:10), | |
pred1 = c(rep(0.5,10)), | |
pred2 = c(0.3, 0.4, 0.5, 0.6, 0.7, | |
1.3, 1.4, 1.5, 1.6, 1.8), | |
obs = c(rep(0.6, 10)), | |
exposure = c(1,2,3,4,5,5,4,3,2,1)) | |
plot_data1<- pouet %>% select(decile, pred1, pred2, obs) %>% | |
gather(key=key, value=value, pred1, pred2, obs) | |
plot1 <- ggplot(data = plot_data1,aes(x=decile, y= value, color= key)) + | |
geom_point() + | |
geom_line() + | |
scale_x_continuous(breaks = seq(1,max(pouet$decile)), | |
limit= range(plot_data1["decile"]) + c(-.5, .5)) + | |
theme(axis.ticks.x = element_blank(), axis.text.x = element_blank(), axis.title.x = element_blank()) + | |
#xlim(range(plot_data1["decile"]) + c(-.5, .5)) + # 0.5 à 10.5.. | |
theme(plot.margin=unit(c(0,0,0,0),'lines')) | |
plot2 <- ggplot(data = pouet, aes(x= decile, y= exposure)) + | |
geom_bar(position='dodge',stat='identity') + | |
theme(plot.margin=unit(c(0.5,0,0,0),'lines'))+ | |
scale_x_continuous(breaks = seq(1,max(pouet$decile))) | |
grobs <- lapply(list(plot1,plot2), FUN=ggplot2::ggplotGrob) | |
max_widths <- do.call(grid::unit.pmax, lapply(grobs, function(x) { x$widths })) | |
num_plots <- length(grobs) | |
for (i in 1:num_plots) { | |
grobs[[i]]$widths <- max_widths | |
} | |
grid.arrange(grobs=grobs , ncol=1, layout_matrix = matrix(c(1,2),nrow=2), heights=c(2,1)) |
Author
SimonCoulombe
commented
Sep 19, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment