umair durrani umair durrani - 1 month ago 9
R Question

plotly does not show titles of multiple plots in R

I am trying to layout 2 plots together using

ggplot2
and
plotly
. Here's what I tried:

library(ggplot2)
library(plotly)

mt_mpg <- ggplot(data = mtcars)+
geom_boxplot(aes(x = as.factor(cyl), y = mpg))+
ggtitle("mpg vs cyl")

mt_disp <- ggplot(data = mtcars)+
geom_boxplot(aes(x = as.factor(cyl), y = disp))+
ggtitle("disp vs cyl")

subplot(mt_mpg, mt_disp)


Everything works great but the title of the combined plot only contains "disp vs cyl". I want to include both titles on the top of their corresponding plots. But I don't see any option in
subplot()
command to do so. Any ideas how this can be fixed? Thanks.

bcd bcd
Answer

one way is to use facet_wrap instead of ggtitle. For example:

df <- mtcars
df$lab1 <- 'mpg vs cyl'
df$lab2 <- 'disp vs cyl'

mt_mpg <- ggplot(df)+
  geom_boxplot(aes(x = as.factor(cyl), y = mpg))+
  facet_wrap(~lab1)

mt_disp <- ggplot(df)+
  geom_boxplot(aes(x = as.factor(cyl), y = disp))+
  facet_wrap(~lab2)

subplot(mt_mpg, mt_disp)

Cheers,

Branden

Comments