防止在条形图中切断长的x轴刻度标签,图中为R

时间:2016-06-29 16:51:20

标签: r plot plotly

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

Plotly chart axis

通过plotly轴的属性列表,我尝试过设置tickangle(我现在没有意义)和其他几个,但是一切都没用。

2 个答案:

答案 0 :(得分:21)

您可以在layout功能中以图形布局调整边距。

可重复的例子,因为没有提供:

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

您可以在margin layout参数的默认值中调整底边距。 margin采用命名列表,其中b是“底部”边距的名称。 160 px适用于此示例,但您可能需要找到适用于标签的值。

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

enter image description here

答案 1 :(得分:0)

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。 Value Labels Truncated

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

Truncation removed after adding cliponaxis = FALSE

希望这会有所帮助