gpt4 book ai didi

r - 如何在ggplot2中标注x轴下的组信息

转载 作者:行者123 更新时间:2023-12-02 01:03:03 24 4
gpt4 key购买 nike

例如:

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="")

enter image description here

而我想要的是在x轴下添加组信息。 enter image description here

最佳答案

使用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 = "")

关于r - 如何在ggplot2中标注x轴下的组信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49287322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com