与ggplot geom_bar的比例

W W*_*W W 8 r ggplot2

与ggplot最简单的方法是什么?

在此输入图像描述

我是否需要调用prop.table或者是否有更简单的方法?

可复制的例子:

x <- c("good", "good", "bad", "bad", "bad", "bad", "perfect", "perfect", "perfect")
y <- c("exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3")
dt <- data.frame(x, y)

ggplot(dt, aes(x, fill = y)) + geom_bar()
Run Code Online (Sandbox Code Playgroud)

Mic*_*per 13

这与这里的上一个问题类似。您可以position = "fill"在ggplot中使用参数将条形图缩放到100%的高度。该scale_y_continuous(labels = scales::percent)命令将频率范围从0-1更改为0-100%。

library(ggplot2)

x <- c("good", "good", "bad", "bad", "bad", "bad", "perfect", "perfect", "perfect") 
y <- c("exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3") 
dt <- data.frame(x, y)

# Build plot
ggplot(dt, aes(x, fill = y)) +
  geom_bar(position = "fill") +
  scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 我发现不需要使用`table`...Al ya需要做的是在`geom_bar`的参数中添加`position =“fill”`:O (2认同)