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

kevw22 picture kevw22 · Jun 29, 2016 · Viewed 19.5k times · Source

I am trying to use plotly to plot a bar chart with long strings as x-axis labels. However, these strings are cut off by plotly like this shown here:

Plotly chart axis

Going through the list of attributes of plotly axis, I've tried setting such as tickangle (which doesn't make sense, I realize now) and several others, but all are of no use.

Answer

Jota picture Jota · Jun 29, 2016

You can adjust the margins in a plotly layout in the layout function.

Reproducible example since one was not provided:

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

If you plot this with the default margins, the labels will be cutoff:

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

You can adjust the bottom margin from the default in the margin argument of layout. margin takes a named list where b is the name for the "bottom" margin. 160 px works in this example, but you may need to find a value that works for your labels.

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

enter image description here