使用 ggplotly() 时换行轴标签
Wrap axis label when using ggplotly()
我正在尝试使用 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")
您可以在 theme
中使用 plot.margin
更改 ggplot 的边距:
ggplotly({
ggplot(df, aes(a, b)) +
geom_col() +
coord_flip() + theme(plot.margin = margin(0,0,0,-4, "cm"))
})
与@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))
我正在尝试使用 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")
您可以在 theme
中使用 plot.margin
更改 ggplot 的边距:
ggplotly({
ggplot(df, aes(a, b)) +
geom_col() +
coord_flip() + theme(plot.margin = margin(0,0,0,-4, "cm"))
})
与@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))