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

标签 r ggplot2

例如:

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/

相关文章:

r - 如何使这个 R 包的输出静音?

r - 使用第二个数据框中的值过滤数据框

r - geom_errorbar 上为正均值,下为负均值

r - 如何使用 geom_text 在堆叠条形图的比例尺上添加频率或数字?

r - Shinydashboard dashboardHeader 中的登录按钮

r - 求和矩阵的元素

r - 如何使用不同的点大小来表示该点所在位置的数量

r - 使用 ggplot2 对来自 3 个不同数据集的 3 个图进行分面

r - 类别内观测值比例的 ggplot 绘图

r - 如何将所有图例保留在 ggplot 中