【问题标题】:Plotly R - order data on y axis based on numeric value (x axis)Plotly R - 根据数值(x 轴)在 y 轴上排序数据
【发布时间】:2021-12-29 12:22:38
【问题描述】:

我有这些数据:

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。

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    一种选择是以您想要的顺序手动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")
      )
    

    【讨论】:

    • Tnx。解决了 ;) 我确实尝试过使用安排,但忘记将 categoryorder 更改为“trace”
    猜你喜欢
    • 2013-02-24
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2022-09-25
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多