Claud H Claud H -4 years ago 73
R Question

plot_ly barplot messes up the order on the x axis

When doing a bar plot with

, I stumbled on a weird output from plotly doing pca analysis graphs: when there are more than 9
's on the X axis, it shows them in a weird order. See the sample and the output below:

[1] "PC1" "PC2" "PC3" "PC4" "PC5" "PC6" "PC7" "PC8" "PC9" "PC10" "PC11" "PC12"
[1] 0.278889072 0.132174191 0.114264338 0.090405125 0.081273614 0.078230246 0.064104021 0.060324481 0.046375086
[10] 0.028577782 0.023676285 0.001705759
plot_ly(type = "bar", x = colnames(rv$pca_prep$x), y =rv$pca_explained)

plot_ly output image

After some research I figured out that that plotly probably uses lexographical scoping. Is there an easy way to change it into the needed numeric one? Is there an easy workaround? Thanks in advance.

Answer Source

plot_ly is sorting your input to x the same way base::sort would. Per @Sebastian' s comment you can use factor in your plot_ly call to overcome this issue but by default factor will also have the same sort behavior. You can use factor's levels argument to specify the order of the factor levels and get your desired behavior.

#fake data with names similiar to question vars
pca_explained <- sort(abs(rnorm(12)), decreasing = TRUE)
col_names     <- paste0("P", seq_along(pca_explained))

#plotly call with factor(x, levels=x)
plotly::plot_ly(type = "bar", 
                x    = factor(col_names, levels=col_names), 
                y    = pca_explained)


plotly output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download