如何修改我的 ggplot2 代码,使条形图彼此相邻而不是堆叠在一起?
How to modify my ggplot2 codes so that the bars are next to each other rather being stacked?
我在 R
中有以下 ggplot2
代码 运行。我需要调整代码,使每个 FY
值的条形图彼此相邻,而不是堆叠在一起。
我的代码如下:
p1 <- ggplot(dff3, aes(x=Gender, fill=FY)) + ggtitle("Gender") +
xlab("Gender") +
geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5) +
ylab("Percentage") +
coord_flip() +
theme_minimal() +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"))
p1
情节是这样的:
最近像这样:
您可以在 geom_bar()
中使用 position_dodge()
。这是一个使用 mtcars
数据集的示例:
library(tidyverse)
ggplot(mtcars, aes(x=factor(am), fill=factor(vs))) +
ggtitle("Gender") +
xlab("Gender") +
geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5, position = position_dodge()) +
ylab("Percentage") +
coord_flip() +
theme_minimal() +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"))
我在 R
中有以下 ggplot2
代码 运行。我需要调整代码,使每个 FY
值的条形图彼此相邻,而不是堆叠在一起。
我的代码如下:
p1 <- ggplot(dff3, aes(x=Gender, fill=FY)) + ggtitle("Gender") +
xlab("Gender") +
geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5) +
ylab("Percentage") +
coord_flip() +
theme_minimal() +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"))
p1
情节是这样的:
您可以在 geom_bar()
中使用 position_dodge()
。这是一个使用 mtcars
数据集的示例:
library(tidyverse)
ggplot(mtcars, aes(x=factor(am), fill=factor(vs))) +
ggtitle("Gender") +
xlab("Gender") +
geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5, position = position_dodge()) +
ylab("Percentage") +
coord_flip() +
theme_minimal() +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"))