我在两个动物园的动物里都有一个数据框。现在这些动物被重复了。当我使用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')
答案 0 :(得分: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)