对于以下数据集,
Genre Amount
Comedy 10
Drama 30
Comedy 20
Action 20
Comedy 20
Drama 20
我想构建一个ggplot2折线图,其中x轴为
Genre
y 轴是所有金额的总和(以 Genre
为条件)。我尝试了以下方法:
p = ggplot(test, aes(factor(Genre), Gross)) + geom_point()
p = ggplot(test, aes(factor(Genre), Gross)) + geom_line()
p = ggplot(test, aes(factor(Genre), sum(Gross))) + geom_line()
但无济于事。
最佳答案
如果您不想在绘图前计算新的数据框,您可以使用 stat_summary
在 ggplot2 中。例如,如果您的数据集如下所示:
R> df <- data.frame(Genre=c("Comedy","Drama","Action","Comedy","Drama"),
R+ Amount=c(10,30,40,10,20))
R> df
Genre Amount
1 Comedy 10
2 Drama 30
3 Action 40
4 Comedy 10
5 Drama 20
您可以使用
qplot
与 stat="summary"
争论 :R> qplot(Genre, Amount, data=df, stat="summary", fun.y="sum")
或添加
stat_summary
到基地 ggplot
形象的 :R> ggplot(df, aes(x=Genre, y=Amount)) + stat_summary(fun.y="sum", geom="point")
关于r - 绘制汇总统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5217616/