使用 R 中的 plotly 防止长 x 轴刻度标签在条形图中被切断

Prevent long x-axis ticklabels from being cut off in bar charts with plotly in R

我正在尝试使用 plotly 绘制带有长字符串作为 x 轴标签的条形图。但是,这些字符串被 plotly 截断,如下所示:

浏览 plotly 轴的属性列表,我尝试设置 tickangle (这没有意义,我现在意识到)和其他几个,但都是没用。

您可以在 layout 函数中调整 plotly 布局中的边距。

由于未提供可重现的示例:

d <- data.frame(traitMean = apply(iris[-5], 2, mean))
# long labels
labs <- c("Long name for this", "Long name for that",
          "Long names everywhere", "Petal Width")

如果使用默认边距绘制此图,标签将被截断:

# example where ticklabels are cutoff
plot_ly(y = d[["traitMean"]], x = labs, type = "bar") %>% 
    layout(xaxis = list(tickangle = 45))

您可以在 layoutmargin 参数中调整默认的下边距。 margin 采用命名列表,其中 b 是 "bottom" 边距的名称。 160 像素适用于此示例,但您可能需要找到适用于您的标签的值。

plot_ly(y = d[["traitMean"]], x = labs, type = "bar") %>% 
    layout(margin = list(b = 160), xaxis = list(tickangle = 45))

textposition="outside" 时,文本可能会在横条上被截断。为避免这种情况,在设置边距以修复 y 轴标签截断的同时,设置 cliponaxis = FALSE 以修复值标签截断。

尽管添加了顶部和底部边距以消除 y 轴标签截断,但这是值标签截断的示例:

library(plotly)

plot_ly(
x = c("1. Group 1", "2. Txn","3. AOV","4. Account/Recv CV","5. Cost %","6. Lost %","7. Take Rate","8. Group 2"),
  y = c(3.8,0,0,0,0,0,0,3.8),
  name = "SF Zoo",
  type = "waterfall",
  measure = c("relative", "relative", "relative", "relative", "relative", "relative", "relative","total"),
  text = c(3.8,0,0,0,0,0,0,3.8), textposition = 'outside'
) %>% 
layout(margin = list(b = 20,t=20))

结果图的截止值为 3.8。

当您添加 cliponaxis = FALSE 时,截断被移除

plot_ly(
  x = c("1. Group 1", 
        "2. Txn",
        "3. AOV",
        "4. Account/Recv CV",
        "5. Cost %",
        "6. Lost %", 
        "7. Take Rate",
        "8. Group 2"),
  y = c(3.8,0,0,0,0,0,0,3.8),
  name = "SF Zoo",
  type = "waterfall",
  measure = c("relative", "relative", "relative", "relative", "relative", "relative", "relative","total"),
  text = c(3.8,0,0,0,0,0,0,3.8), textposition = 'outside', cliponaxis = FALSE
) %>% 
layout(margin = list(b = 20,t=20))

希望对您有所帮助