[英]r ggplot2 barplot groups labels don't stack
有了这个数据,R(ggplot2)中的以下代码:
vars <- read.csv(file="c:/R/rr.csv", header=TRUE, sep=",")
str(vars)
ggplot(vars , aes(x=B, y=ï..A, group = C, fill = C))+
geom_bar(stat="identity", show.legend = F, position=position_stack(0.5)) +
geom_text(aes(label=ï..A), position = position_stack(0.5))+
xlab("year") + ylab("Total")
生成此图: Barplot如何求和来自同一类别的值,例如,500 和 500 来自同一类别,我认为它们应该加起来以在条形图中显示 1000。
您可以对变量 B 和 C 的每个组合的变量 A 的值求和,以便每个 x 标签的每个类别都有一个值。
为此,您可以使用dplyr
包及其函数group_by
并summarise
如下:
library(dplyr)
library(ggplot2)
df %>% group_by(B,C) %>% summarise(SumA = sum(A)) %>%
ggplot(aes(x = B, y = SumA, fill = C))+
geom_col(show.legend = FALSE)+
geom_text(aes(label = SumA), position = position_stack(vjust = 0.5))
编辑:在每个条形顶部添加总和
您可以创建两个新数据框,一个用于 B 和 C 函数中 A 的总和,另一个用于 B 函数中 A 的总和,并按如下方式使用它们:
df_sumA <- df %>% group_by(B,C) %>% summarise(SumA = sum(A))
df_SumTotal <- df %>% group_by(B) %>% summarise(SumTotal = sum(A))
ggplot(df_sumA, aes(x = as.factor(B), y = SumA, fill = C))+
geom_col(show.legend = FALSE)+
geom_text(aes(label = SumA), position = position_stack(vjust = 0.5))+
geom_text(inherit.aes = FALSE, data = df_SumTotal,
aes(x = as.factor(B),y = SumTotal, label = SumTotal), vjust = -1, color = "red")+
ylim(0,max(df_SumTotal$SumTotal+50))
它回答你的问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.