一个可能的解决方案:
library(dplyr)
library(ggplot2)
a=c(2015,2010,2010,2010,2015)
b=c(100,20,50,40,170)
c=c(20,40,10,50,60)
d=cbind(a,b,c)
d <- as.data.frame(d)
myplot <- function(d)
{
d1 <- d %>%
group_by(a) %>%
summarise(count = sum(b)) %>%
mutate(col = "b")
d2 <- d %>%
group_by(a) %>%
summarise(count = sum(c)) %>%
mutate(col = "c")
# This is your table
z <- rbind(d1,d2) %>%
arrange(a)
ggplot() +
geom_bar(data = z, aes(x = a, y = count, fill = col),
position = "dodge", stat = "identity") +
scale_x_continuous(breaks=unique(a))
}
myplot(d)
已编辑:
更短的解决方案:
library(dplyr)
library(ggplot2)
library(purrr)
a=c(2015,2010,2010,2010,2015)
b=c(100,20,50,40,170)
c=c(20,40,10,50,60)
d=cbind(a,b,c)
d <- as.data.frame(d)
myplot <- function(d)
{
z <- map_df(c("b","c"),
~ d %>%
group_by(a) %>%
summarise(count = sum(!!sym(.x))) %>%
mutate(col = .x))
ggplot() +
geom_bar(data = z, aes(x = a, y = count, fill = col),
position = "dodge", stat = "identity") +
scale_x_continuous(breaks=unique(a))
}
myplot(d)