问题
I have a set of data that looks like that (just way bigger):
2 7
3 9
5 3
2 4
7 3
3 4
2 2
and I would like to produce a histogram with bars at 2 of height (7+4+2), so 13, at 3 of height 13, 5 at 3 and 7 at 3.
I hope the question is not too dumb, but the tutorials I found did not discuss this problem. Thanks for any help in advance.
回答1:
DF <- read.table(text="2 7
3 9
5 3
2 4
7 3
3 4
2 2")
library(ggplot2)
ggplot(DF,aes(x=V1,y=V2)) +stat_summary(fun.y=sum,geom="bar")

回答2:
If you want to get the aggregated sums out of the data and plot them later (the ggplot solution does it all) then, starting from DF:
> aggregate(V2~V1,data=DF,sum)
V1 V2
1 2 13
2 3 13
3 5 3
4 7 3
回答3:
Other answers given here probably already answer your question, but for the sake of completeness, if you do not wish to depend on the ggplot
package (I cannot really think of a reason for this, but you might) you could use a combination of aggregate
and barplot
.
> ADF <- aggregate(DF$V2, by = list(V1=DF$V1), FUN = sum)
> barplot(ADF$x, names.arg=ADF$V1)
来源:https://stackoverflow.com/questions/16583315/creating-a-histogram-with-the-number-of-occurrences-at-multiple-places