【问题标题】:R Stackbar plot with Binary variables带有二进制变量的 R 堆积条形图
【发布时间】:2019-11-19 02:07:00
【问题描述】:

我想用ggplot,我的数据就是这样

x <- c(TRUE,FALSE,FALSE,TRUE,TRUE,FALSE) #Logical
y <- c(0,1,1,0,1,0) #Numeric
dat <- data.frame(x,y)

我想创建一个显示百分比的堆积条形图...这似乎应该是一个简单的问题,但不知何故我把它搞砸了,找不到直接的答案。

我试过了

ggplot(data = dat, aes(x = x, y = y, fill = y))+geom_bar(position = 'fill', stat = 'identity')


ggplot(data = dat, aes(x = x, y = factor(y), fill = y))+geom_bar(position = 'fill', stat = 'identity')

第二个看起来更近了,但轴将所有内容压缩到总和为 0?

【问题讨论】:

    标签: r ggplot2 stacked-chart


    【解决方案1】:

    position = 'stack'y-axis 设置为sumy 值,如下所示:

    ggplot(data = dat, 
           aes(x = x, y = sum(y), fill = y)) +
           geom_bar(position = 'stack', stat = 'identity')
    

    希望你觉得它有用。

    【讨论】:

      【解决方案2】:

      试试:

      ggplot(data = dat, aes(x = x, fill = factor(y))) +
        geom_bar()
      

      特别是,geom_bar() 的聚合有一个默认值,以计算行数 (stat = "count")。当您已经预先计算了计数时,您将使用 stat = "identity"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-05
        • 1970-01-01
        • 2020-07-17
        • 1970-01-01
        • 1970-01-01
        • 2017-10-31
        • 1970-01-01
        相关资源
        最近更新 更多