Plotly R - 根据数值(x 轴)在 y 轴上排序数据

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

我有这个数据:

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

我想做简单的 Plotly 点图,我想使用以下代码通过 Inv 变量(x 轴)在 y 轴上排序数据:

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

您可以看到,虽然我将这部分代码放在 layout(xaxis = list(title = "HAMAG - ukupna ulaganja"), yaxis = list(title=F, categoryorder = "total ascending")) - 但我没有得到想要的结果。一些变量已排序,但 y 轴上的一些变量未根据 x 值排序:例如ZGZ (2B) 高于 GZ (5B),BB 高于 KA,尽管它在 x 上的值较小。有人看到我的错误吗? tnx.

一个选项是按照您想要的顺序手动 arrange 您的数据集,并将 categoryorder 设置为 "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")
  )