如何绘制特定行id的总和

时间:2018-04-13 09:45:05

标签: r ggplot2

我有一些像这样的表

Location  Profit
Europe    8000
Asia      3200
Africa    4000
Americas  1800
Europe    3200
Europe    8000
Asia      3200
Oceania   1000
Africa    4000
Europe    3200
Europe    8000
Asia      3200
Africa    4000
Europe    3200

我想创建一个图表,它将结合“欧洲”地区的所有利润。

我怎么能用ggplot做到这一点?

2 个答案:

答案 0 :(得分:2)

如果要绘制按其他列分组的列的总计,可以先使用aggregate

library(ggplot2)

ggplot(aggregate(Profit ~ Location, dat, sum), aes(Location, Profit)) +
    geom_bar(stat = "identity")

请注意,您还可以先计算聚合的data.frame,然后在agg的调用中使用结果ggplot

agg <- aggregate(Profit ~ Location, dat, sum)

数据

dat <-
structure(list(Location = structure(c(4L, 3L, 1L, 2L, 4L, 4L, 
3L, 5L, 1L, 4L, 4L, 3L, 1L, 4L), .Label = c("Africa", "Americas", 
"Asia", "Europe", "Oceania"), class = "factor"), Profit = c(8000L, 
3200L, 4000L, 1800L, 3200L, 8000L, 3200L, 1000L, 4000L, 3200L, 
8000L, 3200L, 4000L, 3200L)), .Names = c("Location", "Profit"
), class = "data.frame", row.names = c(NA, -14L))

答案 1 :(得分:1)

除了@RuiBarradas方法,我们还可以使用stat_summary

library(ggplot2)
ggplot(dat, aes(Location, Profit)) + 
       stat_summary(fun.y = "sum", geom = "bar")

enter image description here