简体   繁体   中英

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

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"))

重叠的标题

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 ggplot


plotly

阴谋地

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM