带有二元变量的 R 堆积条形图
R Stackbar plot with Binary variables
我想用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?
尝试:
ggplot(data = dat, aes(x = x, fill = factor(y))) +
geom_bar()
特别是,geom_bar()
有一个默认的聚合计算行数 (stat = "count"
)。当您已经预先计算了计数时,您将使用 stat = "identity"
。
将 position = 'stack'
和 y-axis
设置为 y
值的 sum
,如下所示:
ggplot(data = dat,
aes(x = x, y = sum(y), fill = y)) +
geom_bar(position = 'stack', stat = 'identity')
希望你觉得有用。
我想用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?
尝试:
ggplot(data = dat, aes(x = x, fill = factor(y))) +
geom_bar()
特别是,geom_bar()
有一个默认的聚合计算行数 (stat = "count"
)。当您已经预先计算了计数时,您将使用 stat = "identity"
。
将 position = 'stack'
和 y-axis
设置为 y
值的 sum
,如下所示:
ggplot(data = dat,
aes(x = x, y = sum(y), fill = y)) +
geom_bar(position = 'stack', stat = 'identity')
希望你觉得有用。