我有一个如下数据框:
id month type count
___ _______ ______ ______
1 1 1 10
1 1 2 09
1 1 3 26
1 2 1 60
1 2 2 90
2 2 3 80
2 1 1 10
2 1 2 09
2 1 3 26
2 2 1 60
2 2 2 90
2 2 3 80
3 1 1 10
3 1 2 09
3 1 3 26
3 2 1 60
3 2 2 90
3 2 3 80
所以我尝试了
ggplot(df,aes(x=id,y=count,fill=month))+geom_bar(stat="identity",position=position_dodge())+geom_text(aes(label=count),size=3)
这给出了一个与我的期望有点不同的情节。感谢任何帮助。
答案 0 :(得分:3)
假设您要将id
绘制为x轴,并排绘制月份,并堆叠不同类型,您可以逐月拆分数据,并为每个月添加一个条形图层,转移{ {1}}第二个月的金额,因此它们可以分开:
x
给出:
barwidth = 0.35
month_one <- filter(df, month == 1) %>%
group_by(id) %>% arrange(-type) %>%
mutate(pos = cumsum(count) - count / 2) # calculate the position of the label
month_two <- filter(df, month == 2) %>%
group_by(id) %>% arrange(-type) %>%
mutate(pos = cumsum(count) - count / 2)
ggplot() +
geom_bar(data = month_one,
mapping = aes(x = id, y = count, fill = as.factor(type)),
stat="identity",
position='stack',
width = barwidth) +
geom_text(data = month_one,
aes(x = id, y = pos, label = count )) +
geom_bar(data = filter(df, month==2),
mapping = aes(x = id + barwidth + 0.01, y = count, fill = as.factor(type)),
stat="identity",
position='stack' ,
width = barwidth) +
geom_text(data = month_two,
aes(x = id + barwidth + 0.01, y = pos, label = count )) +
labs(fill = "type")
答案 1 :(得分:2)