Thomas Neitmann
Thomas Neitmann

Reputation: 2722

Wrap axis label when using ggplotly()

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

Upvotes: 0

Views: 944

Answers (2)

Thomas Neitmann
Thomas Neitmann

Reputation: 2722

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

Upvotes: 0

asafpr
asafpr

Reputation: 357

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

Upvotes: 1

Related Questions