Skip to content

Subtitles with ggplotly

Martina Morris edited this page Nov 13, 2021 · 1 revision

Not all of the plot options in ggplot end up being properly processed with ggplotly. One example is subtitles.

Reprex showing the disappearing subtitle:

df = data.frame(xval=1:10, 
                yval=sample(1:10, 10), 
                zval=sample(c("this", "that"), 10, replace=T))

p <- ggplot(data = df,
            aes(x=xval, y=reorder(yval, xval), 
                text=paste("Group: ", zval))) +
  geom_bar(stat="identity", fill="lightsteelblue") +
  
  labs(title = "Example of subtitle",
       subtitle = "Subtitle with ggplotly",
       x = "x axis",
       y = "y axis")

p # subtitle visible

ggplotly(p, tooltip = "text") # now it's gone!

The fix is to use the layout function in plotly. Reprex:

# Set up margin values

m <- list(
    l = 80,
    r = 80,
    b = 80,
    t = 80,
    pad = 0
  )

# Pass it to plotly

df = data.frame(xval=1:10, 
                yval=sample(1:10, 10), 
                zval=sample(c("this", "that"), 10, replace=T))

p <- ggplot(data = df,
            aes(x=xval, y=reorder(yval, xval), 
                text=paste("Group: ", zval))) +
  geom_bar(stat="identity", fill="lightsteelblue") +
  
  labs(x = "x axis", # don't specify the title/subtitle here
       y = "y axis")

ggplotly(p, tooltip = "text") %>%
  layout(
    title = list(
      text = paste0('Example of subtitle', # specify them here
                    '<br>',
                    '<sup>',
                    'Subtitle with ggplotly',
                    '</sup>'),
      x=0.09), # this controls the position of the title, default is center
      margin=m)