【问题标题】:Plotting summary statistics绘制汇总统计
【发布时间】:2011-07-10 05:04:09
【问题描述】:

对于以下数据集,

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()

但无济于事。

【问题讨论】:

    标签: r ggplot2 summarization


    【解决方案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()
    

    【讨论】:

    • 您是否从问题中提供的示例中自动生成了您的结构()指令?如果是的话,我很高兴知道如何:-)
    • 不是,我是手动输入的,所以在上面加上dput
    • 但是您可以使用 psych 包中的 read.clipboard 函数。它就像一个魅力:dtf &lt;- read.clipboard()。谢谢你提醒我。
    • 啊,是的,太好了。对我来说,选择数据和read.table("clipboard",header=TRUE) 就可以了。谢谢!
    • 您也可以将?textConnectionread.table 结合使用。 SO上有一些例子,例如stackoverflow.com/questions/4881149/r-list-row-name
    【解决方案2】:

    如果您不想在绘图之前计算新的数据框,您可以在 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
    

    您可以使用 qplotstat="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")
    

    【讨论】:

    • 简洁的单行...尽管您可以轻松省略 factor,因为 stringsAsFactors 是默认行为。
    • 我想我会让 factor() 指令,因为它在问题中使用,但你是对的,它在这里没有用。谢谢指点。
    • 非常感谢,我使用 factor 的原因是因为我试图将总和从低到高,但它没有这样做。
    • 好吧,我终于把它删掉了:)
    • 看来您可以在您的aes 定义中使用reorder 调用,例如`aes(x=reorder(Genre, Amount, sum), y=Amount))`。但可能有更好、更清洁的方法来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多