I want to add some text above a interactive plotly in R. I wanted to do this by transforming my text to an html widget and combining two widgets (to have good control of the spacing). I used the code below with manipulateWidget::combineWidgets. It works well except that the colour scale that I use is changed for another one, with a legend that does not match the colour on the plot.
I also tried with layout parameter in plotly but I found hard to deal with spacing when the text on top has multiple rows (it was sometimes written on the plot).
Do you know why this happens and if it can be fixed? Or if there is another way to add a box of html text above a plotly?
DF <- data.frame(Month=c(5:8), Year=rep(2024,4), Value=c(3,5,1,8))
Pop <- ggplot(DF)+
geom_tile(aes(x=Month, y=Year, fill=Value))+
theme_minimal()+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_fill_viridis_c(name="Name")
Pop_ly <- Pop %>%
ggplotly(., tooltip="text") %>%
layout(xaxis = list(fixedrange = TRUE), yaxis = list(fixedrange = TRUE)) %>%
config(displayModeBar = F)
manipulateWidget::combineWidgets(list = list(HTML("TEST"), Pop_ly), rowsize=c(1,5))
I don't know why this happens, but you can always construct a HTML Widget using htmltools
, e.g. like
library(htmltools)
browsable(div(HTML("<H1>Test</H1>"), Pop_ly))
this will wrap the H1-element Test
and your plotly element inside a div
Here is a full code example:
library(ggplot2)
library(plotly)
DF <- data.frame(Month=c(5:8), Year=rep(2024,4), Value=c(3,5,1,8))
Pop <- ggplot(DF)+
geom_tile(aes(x=Month, y=Year, fill=Value))+
theme_minimal()+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_fill_viridis_c(name="Name")
Pop_ly <- Pop %>%
ggplotly(., tooltip="text") %>%
layout(xaxis = list(fixedrange = TRUE), yaxis = list(fixedrange = TRUE)) %>%
config(displayModeBar = F)
library(htmltools)
widget <- div(HTML("<H1>Title</H1>",paste(rep("This is a longer text that might wrap and might be written on the Plot. ",4), collapse = " ")), Pop_ly)
# save
save_html(widget, "output.html")
# browse
browsable(widget)