简体   繁体   English

使用 ggplotly() 时包装轴标签

[英]Wrap axis label when using ggplotly()

I am trying to create a horizontal bar chart using ggplotly() .我正在尝试使用ggplotly()创建一个水平条形图。 Because the labels are rather long I inserted HTML line breaks <br> .因为标签很长,我插入了 HTML 换行符<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.当使用ggplotly()绘制数据时,标签确实被包装了,但标签左侧有很大的边距,基本上使包装无用。 Is there any way to fix this besides using plot_ly() ?除了使用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()
})

在此处输入图片说明

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

在此处输入图片说明

You can change the margins of the ggplot with plot.margin in theme :您可以更改ggplot的边缘与plot.margintheme

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

在此处输入图片说明

Similarly to @asafpr's answer, adjusting the left margin using plotly::layout() does the job:与@asafpr 的回答类似,使用plotly::layout()调整左边距可以完成这项工作:

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

在此处输入图片说明

Interestingly, the value passed onto l does not seem to matter:有趣的是,传递给l的值似乎并不重要:

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

在此处输入图片说明

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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