我已经创建了一张条形图并按照所需的顺序排列了x轴。然而,一旦我通过facet_nested运行它,它就会改变顺序。
这是我的文件样式:
file:
drug P_resistant G_resistant
DrugA 18 16
DrugB1 430 425
DrugB2 156 154
DrugB3 0 0
DrugC1 60 56
DrugC2 66 64
DrugC3 113 111
DrugC4 250 248
为了按照类型、类别和药品顺序排列订单:
library(ggplot2)
library(tidyr)
library(dplyr)
library(ggrepel)
library(forcats)
library(data.table)
library(ggnomics)
library(scales)
library(survival)
library(tidytext)
file.g <- gather(file, type, value, -drug)
##this is for facet "group"
file.g$group <-c("87.51%","98.85%","98.71%","NA","93.2%","96.9%","98.2%","99%","87.51%","98.85%","98.71%","NA","93.2%","96.9%","98.2%","99%")
##this is for facet "class"
file.g$class <- c(rep("Class A",1),rep("Class B",3),rep("Class C",4),rep("Class A",1),rep("Class B",3),rep("Class C",4))
## the order of drug appearance on x-axis
file.g$drug_order<- c(4,1,2,3,5,6,7,8,4,1,2,3,5,6,7,8)
因此,当您查看 file.g 时,它将如下所示:
drug type value group class drug_order
DrugA P_resistant 18 87.51% Class A 4
DrugB1 P_resistant 430 98.85% Class B 1
DrugB2 P_resistant 156 98.71% Class B 2
DrugB3 P_resistant 0 NA Class B 3
DrugC1 P_resistant 60 93.2% Class C 5
DrugC2 P_resistant 66 96.9% Class C 6
DrugC3 P_resistant 113 98.2% Class C 7
DrugC4 P_resistant 250 99% Class C 8
DrugA G_resistant 16 87.51% Class A 4
DrugB1 G_resistant 425 98.85% Class B 1
DrugB2 G_resistant 154 98.71% Class B 2
DrugB3 G_resistant 0 NA Class B 3
DrugC1 G_resistant 56 93.2% Class C 5
DrugC2 G_resistant 64 96.9% Class C 6
DrugC3 G_resistant 111 98.2% Class C 7
DrugC4 G_resistant 248 99% Class C 8
以下代码按照我的要求排列x轴:
药品B1、药品B2、药品B3、药品A、药品C1、药品C2、药品C3、药品C4。
file.g$type <- factor(file.g$type, levels=c("P_resistant","G_resistant"))
file.g$class <- factor(file.g$class, levels= c("Class B", "Class A", "Class C"))
##main script
p<-ggplot(file.g, aes(fill=type, x=reorder_within(drug, drug_order, class), y=value)) +
geom_bar(aes(fill = type), stat = "identity", position = "dodge", colour="white") +
geom_text(aes(label=value), position=position_dodge(width=1.2), vjust=-0.5)+
scale_fill_manual(values=c("#af8dc3","#7fbf7b")) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 500)) +
theme(title = element_text(size = 18), legend.text=element_text(size=12), axis.text.x=element_text(size=9), axis.text.y =element_text(size=15)) +
theme(plot.title = element_text(hjust = 0.5))+
scale_x_reordered()
但是当我使用嵌套分面搜索时运行它
p+facet_nested(.~class+group, scales= "free_x", space= "free_x")+
theme(strip.text.x = element_text(size = 7.5))
这将改变x轴的顺序为:
DrugB2、DrugB1、DrugB3、DrugA、DrugC1、DrugC2、DrugC3、DrugC4。
我已经被困在这里几个小时了...非常感谢任何帮助或想法。
ggplot
函数中,你使用了drug.g
数据集,但在你的代码中没有提到。最后,我建议你添加一个清晰的期望输出模型,因为也许你可以得到一个不使用你正在使用的函数的解决方案。 - s__