0

I am trying to create a horizontal bar chart using ggplotly(). Because the labels are rather long I inserted HTML line breaks <br>. When plotting the data using ggplotly() the label is indeed wrapped but there is big margin to the left of the label basically rendering the wrapping useless. Is there any way to fix this besides using plot_ly()?

library(ggplot2)
library(plotly)

df <- data.frame(a = "A very long label<br>that needs<br>to be wrapped", b = 10)

ggplotly({
  ggplot(df, aes(a, b)) +
  geom_col() +
  coord_flip()
})

enter image description here

plot_ly(df, y = ~a, x = ~b, type = "bar", orientation = "h")

enter image description here

Thomas Neitmann
  • 2,552
  • 1
  • 16
  • 31
  • [This answer on How to maintain size of ggplot with long labels](https://stackoverflow.com/a/41607201/3817004) elaborates different options for `ggplot2` which may work for `ggplotly` as well. – Uwe Jan 07 '20 at 15:42

2 Answers2

1

You can change the margins of the ggplot with plot.margin in theme:

ggplotly({
     ggplot(df, aes(a, b)) +
         geom_col() +
         coord_flip() + theme(plot.margin = margin(0,0,0,-4, "cm"))
 })

enter image description here

asafpr
  • 347
  • 1
  • 5
0

Similarly to @asafpr's answer, adjusting the left margin using plotly::layout() does the job:

library(ggplot2)
library(plotly)

df <- data.frame(a = "A very long label<br>that needs<br>to be wrapped", b = 10)

p <- ggplot(df, aes(a, b)) +
  geom_col() +
  coord_flip()

ggploty(p) %>%
  layout(margin = list(l = 10))

enter image description here

Interestingly, the value passed onto l does not seem to matter:

ggploty(p) %>%
  layout(margin = list(l = 10))

enter image description here

ggploty(p) %>%
  layout(margin = list(l = 1000))

enter image description here

Thomas Neitmann
  • 2,552
  • 1
  • 16
  • 31