EnFiFa
EnFiFa

Reputation: 65

R: Combine subplots into one organism using ggplot and plotly

I have a lot of data with categorical variables that has a lot of levels. This gives me some difficulty plotting them, especially when I put them into Rmarkdown. I am trying to figure out how to best deal with this, and I have found that a combination of ggplot2 and plotly might help me. In my provided example, I am able to zoom in on the x-axis - and tell levels of categories from each other.

I would like some advice on how to better incorporate my subplot with my main plot, see code below:

I wonder if I need to merge these two plots into one, but not sure how to do this better.

# source: https://devcodef1.com/news/1304946/r-markdown-slider-zoom-plots

library(plotly)

set.seed(123)
n_var=70
N=400
data<-data.table(var1=as.character(sample(1:n_var, replace=T,size=N)), 
               var2=sample(1:10, replace=T, size=N),
               response=rnorm(N),
               exposure=rgamma(N, 1))
dt1 <- data[, .(factor=mean(response), 
               exposure=sum(exposure)),
           , by=var1][order(-var1)]
dt2 <- data[, .(factor=mean(response), 
               exposure=sum(exposure)),
           , by=var2][order(-var2)]

# setup for categorical variable
p <- ggplot(dt, aes(x = var1, y = factor)) +
  geom_point() +
  labs(x = "var1", y = "response")

p <- ggplotly(p)

p <- plotly_build(p)

p$x$layout$hovermode <- "closest"
e <- ggplot(dt, aes_string(x = "var1", y = "exposure")) +
  geom_bar(stat = "identity", fill = "steelblue2",
           size = 0.8, alpha = .4) +
  labs(x = "", y = "exposure")  +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_line(color = NA))
subplot(p, e, nrows = 2, margin = 0.04, heights = c(0.8, 0.2))

# setup for continuous variable
p <- ggplot(dt2, aes(x = var2, y = factor)) +
  geom_line() +
  labs(x = "var2", y = "response")

p <- ggplotly(p)

p <- plotly_build(p)

e <- ggplot(data = data, aes(x = var2, weight = exposure)) +
  geom_density(fill = "steelblue2", size = 0.8, alpha = .4) +
  labs(x = "") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_line(color = NA))
subplot(p, e, nrows = 2, margin = 0.04, heights = c(0.8, 0.2))

Upvotes: 0

Views: 65

Answers (1)

EnFiFa
EnFiFa

Reputation: 65

I was unaware of the shareX parameter, that did the trick for me:

p <- ggplot(dt1, aes(x = var1, y = factor)) +
  geom_point() +
  labs(x = "var1", y = "response")

e <- ggplot(dt1, aes(x = var1, y = exposure)) +
  geom_bar(stat = "identity", fill = "steelblue2", alpha = 0.4) +
  labs(x = "", y = "exposure")

# Convert to plotly objects
p_plotly <- ggplotly(p)
e_plotly <- ggplotly(e)

# Combine plots and share x-axis
subplot(p_plotly, e_plotly, nrows = 2, shareX = TRUE, heights = c(0.8, 0.2))

Upvotes: 0

Related Questions