首先,您需要获取包含要绘制的值的摘要dataframe
。
df <- data.frame(V1 = rep(1:2,each=5), V2 = c("A","A","B", "B", "A", "A", "B","A", "A", "A"),
V3 = c(0,0,1,0,1,0,0,0,0,0))
values <- aggregate(df$V3, list(V1 = df$V1, V2 = df$V2), sum)
# V1 V2 V3
# 1 1 A 1
# 2 2 A 0
# 3 1 B 1
# 4 2 B 0
ggplot(values, aes(x = factor(V1), y = V3, fill = V2))+
geom_bar(stat = "identity", width = 0.2)
OR,这一点,如果你不希望他们要在彼此顶部堆叠。添加一些标签。
ggplot(values, aes(x = factor(V1), y = V3, fill = V2))+
geom_bar(stat = "identity", width = 0.2, position = "dodge") +
labs(list(x = "x", y = "count",fill = "group"))
编辑
我试图直接在dataframe
使用ggplot
而不进行汇总,结果都是一样的。
## a little change in V3
df <- data.frame(V1 = rep(1:2,each=5),
V2 = c("A","A","B", "B", "A", "A", "B","A", "A", "A"),
V3 = c(2,0,1,2,1,3,3,8,1,0))
## plot df directly
ggplot(df, aes(factor(V1), V3, fill = V2)) +
geom_bar(stat = "identity", width = 0.2, position = "dodge") +
labs(list(x = "x", y = "count",fill = "group"))
我可能是麻木到Excel,但您可以绘制或显示最后的数字的例子吗? –
谢谢你的补充。 – user95902