使用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()
答案 0 :(得分:7)
这是与之前的here类似的问题。您可以使用ggplot中的position = "fill"
参数将条形缩放到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)
答案 1 :(得分:2)
如果没有可重复的数据,很难回答你的问题,但通常你会想要这样的东西:
library(ggplot2)
ggplot(data = YourData, aes(x = LevelNumVar, y = CountVar, fill = LevelLetterVar)) +
geom_bar(stat = "identity")
其中:LevelNumVar是x轴上的变量,LevelLetterVar是您要着色的变量,CountVar是y轴上的变量。
以下是使用您的数据的代码:
library(dplyr)
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)
dt <- dt %>%
group_by(x, y) %>%
summarise(count = n())
ggplot(dt, aes(x = x, y = count, fill = y)) +
geom_bar(stat = "identity")