【问题标题】:Plot table objects with ggplot?用ggplot绘制表格对象?
【发布时间】:2014-11-06 19:42:49
【问题描述】:

我有这些数据:

         No    Yes
Female  411   130
Male    435   124

它是使用标准 table 命令创建的。现在有了情节,我可以这样绘制:

plot(table(df$gender, df$fraud))

然后它会输出一个 2x2 条形图。

所以我的问题是,我怎样才能用 ggplot2 做到这一点?有没有办法不将表对象转换为数据框?我会这样做,但它会变得一团糟,然后您需要重命名列标题和行标题,这对于真正非常简单的事情变得一团糟?

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    诸如

    之类的东西
    ggplot(as.data.frame(table(df)), aes(x=gender, y = Freq, fill=fraud)) + 
        geom_bar(stat="identity")
    

    得到一个相似的图表,重新标记的次数最少。

    【讨论】:

    • 如果有一个可以看到(情节)和运行(代码)的例子会很有帮助
    【解决方案2】:

    ggplot2 适用于数据框,因此,您必须将表格转换为框架。这是一个示例代码:

    myTable <- table(df$gender, df$fraud)
    myFrame <- as.data.frame(table(myTable))
    

    现在,您可以在 ggplot2 中使用 myFrame:

    ggplot(myFrame, aes(x=gender))+
      geom_bar(y = Freq)
    

    请参阅Coerce to a Data Frame 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      相关资源
      最近更新 更多