【问题标题】:Summarize data by group in Plotly R在 Plotly R 中按组汇总数据
【发布时间】:2019-02-26 20:42:28
【问题描述】:

我有一个数据框,里面有两个动物园里的动物。现在这些动物被重复了。当我使用 plotly 绘制它时,它只取动物的一个值并绘制它。所以即使SF_ZOO 中有 9 只长颈鹿,它也只会显示8。如何按动物分组并显示所有值的总和?

library(plotly)

Animals <- c("giraffes", "orangutans", "monkeys","giraffes", "orangutans", "monkeys")
SF_Zoo <- c(1,4,6,8,9,11)
LA_Zoo <- c(11,13,15,12,15,08)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

p <- plot_ly(data, x = aggregate(~Animals), y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
  add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>%
  layout(yaxis = list(title = 'Count'), barmode = 'group')

【问题讨论】:

    标签: r plotly r-plotly


    【解决方案1】:

    你没有正确使用aggregate;我会先aggregate,然后再绘图

    data.agg <- aggregate(cbind(SF_Zoo, LA_Zoo) ~ Animals, data = data, FUN = sum)
    
    p <- plot_ly(data.agg, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
      add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>%
      layout(yaxis = list(title = 'Count'), barmode = 'group')
    

    或者您可以采用tidyverse 方式并使用ggplotly 进行绘图

    library(tidyverse)
    p <- data %>%
        gather(Zoo, Value, -Animals) %>%
        group_by(Animals, Zoo) %>%
        summarise(Value = sum(Value)) %>%
        ggplot(aes(x = Animals, y = Value, fill = Zoo)) +
        geom_col(position = "dodge2")
    ggplotly(p)
    

    【讨论】:

    • 谢谢。我认为聚合是唯一的选择。我想知道在 plotly 中是否有一个选项来聚合数据。
    • @SNT 我不知道,但我可能错了;一般来说,我认为将数据聚合/抛光/整理和数据可视化分开会更干净。
    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多