Fix plotly ggplotly() Title Overlapping Plot When Title is Split on Two Lines

你离开我真会死。 提交于 2020-07-31 05:11:48

问题


In the example below, the second line of the title overlaps slightly with the plot. Is there a way to fix this by increasing the spacing between the title and plot?

library(ggplot2)
library(plotly)
library(magrittr)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() + 
  ggtitle("A REALLY, REALLY, REALLY LONG TITLE THAT I WANT TO\nSPLIT INTO TWO LINES")
p1

ggplotly() %>% config(collaborate=FALSE, cloud=FALSE, displaylogo=FALSE, modeBarButtonsToRemove=c("select2d", "sendDataToCloud", "pan2d", "resetScale2d", "hoverClosestCartesian", "hoverCompareCartesian", "lasso2d", "zoomIn2d", "zoomOut2d"))


回答1:


Plotly ignores trailing new line characters and also needs HTML breaks <br /> instead of \n for new lines (see example at the end).

Add <br /> to manually break your title and add a top margin to your layout (layout(gp, margin=list(t = 75))).

library(ggplot2)
library(plotly)
library(magrittr)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() + 
  ggtitle("A REALLY, REALLY, REALLY LONG TITLE THAT I WANT TO <br />\nSPLIT INTO TWO LINES<br />\n")
p1

gp <- ggplotly() %>% config(collaborate=FALSE, cloud=FALSE, displaylogo=FALSE, modeBarButtonsToRemove=c("select2d", "sendDataToCloud", "pan2d", "resetScale2d", "hoverClosestCartesian", "hoverCompareCartesian", "lasso2d", "zoomIn2d", "zoomOut2d"))
gp <- layout(gp, margin=list(t = 75))
gp

ggplot


plotly




回答2:


As you can tell, ggplot doesn't recalculate the total absolute height. So, the easiest way to add some buffer space between the title and plot is to simply add an additional newline char (\n) on the end of a long title.

ggtitle("A REALLY, REALLY, REALLY LONG TITLE THAT I WANT TO\nSPLIT INTO TWO LINES\n")



来源:https://stackoverflow.com/questions/42821171/fix-plotly-ggplotly-title-overlapping-plot-when-title-is-split-on-two-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!