代码之家  ›  专栏  ›  技术社区  ›  Andrii

绘图:如何在同一轴上显示离散和非离散数据?

  •  0
  • Andrii  · 技术社区  · 6 年前

    我正在处理以下数据集的堆积条形图,并得到一个错误“不能同时显示离散和;同一轴上的非离散数据”。此外,数据绘制不正确。对于X轴上的每个“月”,我希望按“单位”堆叠条形图,值来自“值”。

    library(data.table)
    library(plotly)
    
    df <- fread(
    '"month","unit","value"
    "2017-01","Unit 1",1064000
    "2017-01","Unit 2",911487
    "2017-02","Unit 1",851200
    "2017-02","Unit 2",656640
    "2017-03","Unit 1",834905
    "2017-03","Unit 2",601920')
    
    df %>%
      plot_ly(x = ~month, y = ~value, type = 'bar', name = "month") %>% 
      add_trace(y = ~unit, name = "unit") %>% 
      layout(yaxis = list(title = 'Units by dates'), barmode = 'stack')
    

    如果有人知道如何在这里制定可行的计划,我将不胜感激。

    谢谢!

    0 回复  |  直到 6 年前
        1
  •  1
  •   tamtam    6 年前

    你不必添加 trace 对于简单的条形图,定义 color

    df %>%
      plot_ly(x = ~month, y = ~value,  color = ~unit, type = "bar") %>% 
      layout(yaxis = list(title = 'Units by dates'), barmode = 'stack')
    

    enter image description here