【问题标题】:Wrap axis label when using ggplotly()使用 ggplotly() 时包装轴标签
【发布时间】:2020-01-07 14:15:06
【问题描述】:

我正在尝试使用ggplotly() 创建水平条形图。因为标签相当长,我插入了 HTML 换行符<br>。当使用ggplotly() 绘制数据时,标签确实被包装了,但标签左侧有很大的边距,基本上使包装无用。除了使用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")

【问题讨论】:

标签: r plotly ggplotly


【解决方案1】:

您可以在theme 中使用plot.margin 更改ggplot 的边距:

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

【讨论】:

    【解决方案2】:

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

    有趣的是,传递给l 的值似乎并不重要:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 2021-12-07
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      相关资源
      最近更新 更多