例如:
library(tidyverse)
library(ggplot2)
library(scales)
set.seed(123)
plotdf<-data.frame(
sid=paste0("S", rep(1:5, each=4)),
n=rbinom(20, 100, 0.3),
types=rep(letters[5:8], 5),
group=c(rep("a", 12), rep("b", 8))
)
sid n types group
1 S1 30 e a
2 S1 26 f a
3 S1 34 g a
4 S1 30 h a
5 S2 38 e a
6 S2 34 f a
7 S2 27 g a
8 S2 36 h a
9 S3 34 e a
10 S3 30 f a
11 S3 25 g a
12 S3 32 h a
13 S4 31 e b
14 S4 29 f b
15 S4 28 g b
16 S4 17 h b
17 S5 27 e b
18 S5 40 f b
19 S5 33 g b
20 S5 24 h b
ggplot(plotdf, aes(x=sid, y=n, fill=types))+
geom_bar(position="fill", stat="identity")+
scale_y_continuous(labels=percent_format())+
theme(axis.text.x = element_text(angle = 90, hjust = 1))+
labs(y="Percent", x="", fill="")
我想要的是在x轴下添加组信息。
最佳答案
使用 facet_grid(~group, scales = "free", switch = "x")
:
ggplot(plotdf, aes(x = sid, y = n, fill = types)) +
geom_bar(position = "fill", stat = "identity") +
facet_grid(~group, scales = "free", switch = "x") +
scale_y_continuous(labels = percent_format())+
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(y = "Percent", x = "", fill = "")