How to add long title in ggplotly

Consider the following example:

data(canada.cities, package = “maps”)
viz <- ggplot(canada.cities, aes(long, lat)) +
borders(regions = “canada”) +
coord_equal() +
geom_point(aes(text = name, size = pop), colour = “red”, alpha = 1/2) +
ggtitle(paste(“Average bill for 1 people \n”,
“Average bill for 2 people \n”,
“Average bill for 3 people \n”,
“Average bill for 4 people”, sep = “”))
ggplotly(viz)

What I want is:

Average bill for 1 people
Average bill for 2 people
Average bill for 3 people
Average bill for 4 people

in the title.

Could you please help?

Hi, so what you could try to do is replace \n with <br>. However the issue will be that the title will start to conflict with your chart.
So in addition to that, you would have to edit the height of the top margin. You can do this with the following commands:

viz2 <- plotly_build(viz)
viz2$layout$margin$t = 100 #note you may have to change this number
# in addition you may also have to change the height and width of the plot
viz2$layout <- c(viz2$layout, list(height=1000, width=1000))
viz2

Thank you so much. It works. However, I am using ggploty(viz) inside of renderPlotly() for developing shiny.

I followed you and wrote:

viz2 <- plotly_build(gplot)
viz2$layout$margin$t = 200 #note you may have to change this number
ggplotly(viz2)

I am getting the error:

Error in UseMethod(“ggplotly”, p) :
no applicable method for ‘ggplotly’ applied to an object of class “plotly_built”

Please help. Thank you for your help.

You don’t have to call ggplotly again, you can just type viz2

Thank you very much. It works. However, when I downloaded the plot produced by plotly, it has the same problem as before, i.e., the title is getting cut off. I appreciate your kind help.

Can you show your code for this?

data(canada.cities, package = “maps”)
viz <- ggplot(canada.cities, aes(long, lat)) +
borders(regions = “canada”) +
coord_equal() +
geom_point(aes(text = name, size = pop), colour = “red”, alpha = 1/2) +
ggtitle(paste(“Average bill for 1 people <br”,
“Average bill for 2 people <br”,
“Average bill for 3 people <br”,
“Average bill for 4 people”, sep = “”))
ggplotly(viz)
viz2 <- plotly_build(viz)
viz2$layout$margin$t = 150 #note you may have to change this number# in addition you may also have to change the height and width of the plot
viz2$layout <- c(viz2$layout, list(height= 600, width= 600))
viz2

I have removed “>” in “<br” for this post, otherwise it was adding new line.

You left out the <br> in the titles. The <br> stands for a linebreak in HTML.

I have removed “>” in “<br” for this post, otherwise it was adding new line.