绘制汇总统计量

5
针对以下数据集,
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()

但是没有任何效果。

2个回答

8

如果你不想在绘图前计算一个新的数据框,你可以使用ggplot2中的stat_summary。例如,如果你的数据集看起来像这样:

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

您可以使用stat="summary"参数调用qplot
R> qplot(Genre, Amount, data=df, stat="summary", fun.y="sum")

或者在基本的ggplot图形中添加一个stat_summary

R> ggplot(df, aes(x=Genre, y=Amount)) + stat_summary(fun.y="sum", geom="point")

我想我会保留factor()指令,因为它在问题中被使用,但你是对的,它在这里没有用。感谢你的指出。 - juba
好的,我终于把它删除了 :) - juba
@juba,有没有办法根据y值排序条形图,这里的y值是总和? - Julio Diaz
2
在您的 aes 定义中,似乎可以使用 reorder 调用,类似于 aes(x=reorder(Genre, Amount, sum), y=Amount))。但是可能还有更好、更清晰的方法来实现。 - juba
stat_方法的完整文档在哪里?《ggplot》书几乎没有涉及到这个,但它们显然是强大而有用的。 - Alex Brown
显示剩余4条评论

1
尝试像这样做:

dtf <- structure(list(Genre = structure(c(2L, 3L, 2L, 1L, 2L, 3L), .Label = c("Action", 
"Comedy", "Drama"), class = "factor"), Amount = c(10, 30, 20, 
20, 20, 20)), .Names = c("Genre", "Amount"), row.names = c(NA, 
-6L), class = "data.frame")

library(reshape)
library(ggplot2)
mdtf <- melt(dtf)
cdtf <- cast(mdtf, Genre ~ . , sum)
ggplot(cdtf, aes(Genre, `(all)`)) + geom_bar()

你是否从问题中提供的示例自动生成了你的structure()指令?如果是,我会很高兴知道如何做 :-) - juba
不,我是手动输入的,因此在其上应用了 dput - aL3xa
但是你可以使用psych包中的read.clipboard函数。它非常好用:dtf <- read.clipboard()。感谢你提醒我这个。 - aL3xa
啊,好的。对我来说,选择数据并使用read.table("clipboard",header=TRUE)就可以了。谢谢! - juba
2
你也可以将?textConnectionread.table结合使用。这里在SO上有一些例子,例如http://stackoverflow.com/questions/4881149/r-list-row-name。 - Roman Luštrik
请查看此处的 text_to_table:https://dev59.com/1W865IYBdhLWcg3wM7q0#3941145 - Richie Cotton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接