Home > Net >  Plotly R - order data on y axis based on numeric value (x axis)
Plotly R - order data on y axis based on numeric value (x axis)

Time:12-30

I have this data:

myData <- data.frame(Zupanija = c('GZ','ZGZ','KZ','VZ','KK','M','BB','VP','PS','BP','OB','VU','KA','SM','PG','LS','ZA','ŠK','SD','IS','DN'), 
                   Inv = c(5205740135,2017069611,568884637,908563032,487561769,735161926,284291246,195329869,257799660,295494321,721957349,383617802,464253852,298576348,1182794616,277411269,677612459,405016102,3041655541,1039402830,642317513)) 

I want to do simple Plotly point graph and I would like to order data on y axis by the Inv variable (x axis) with this code:

 myData %>%
plot_ly(x = ~Inv, y = ~ Zupanija) %>% 
add_trace(type = 'scatter',
          mode = 'markers',
          stroke = I("black"),
          span = I(1),
          size= ~ sqrt(Inv),
          color = ~ sqrt(Inv),
          colors = inferno(50, alpha = 1, begin = 0, end = 1, direction = 1),
          alpha = 1,
          showlegend = FALSE)%>% 
hide_colorbar()%>%
layout(xaxis = list(title = "HAMAG - ukupna ulaganja"),
       yaxis = list(title=F, categoryorder = "total ascending"))

enter image description here

You can see that altough I put this part of the code layout(xaxis = list(title = "HAMAG - ukupna ulaganja"), yaxis = list(title=F, categoryorder = "total ascending")) - I do not get wanted result. Some variables are sorted but some variables on the y axis are not sorted based on x value: e.g. ZGZ (2B) is above GZ (5B) and BB is above KA, although it has smaller value on x. Does anyone see my mistake? tnx.

CodePudding user response:

One option would be to manually arrange your dataset in your desired order and setting the categoryorder to "trace":

library(plotly)
library(viridis)

myData %>%
  arrange(reorder(Zupanija, Inv)) %>% 
  plot_ly(x = ~Inv, y = ~Zupanija) %>%
  add_trace(
    type = "scatter",
    mode = "markers",
    stroke = I("black"),
    span = I(1),
    size = ~ sqrt(Inv),
    color = ~ sqrt(Inv),
    colors = inferno(50, alpha = 1, begin = 0, end = 1, direction = 1),
    alpha = 1,
    showlegend = FALSE
  ) %>%
  hide_colorbar() %>%
  layout(
    xaxis = list(title = "HAMAG - ukupna ulaganja"),
    yaxis = list(title = F, categoryorder = "trace")
  )

  • Related