Как заказать ось X в Facet_nested - PullRequest
       97

Как заказать ось X в Facet_nested

2 голосов
/ 04 октября 2019

Я создал барплот и расположил ось 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 так, как я хочу:

DrugB1, DrugB2, DrugB3, DrugA, DrugC1, DrugC2, DrugC3, DrugC4

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()

Image 1

Но когда я запускаю это через вложенный фасет

p+facet_nested(.~class+group, scales= "free_x", space= "free_x")+
  theme(strip.text.x = element_text(size = 7.5))

Image2

изменяет порядок оси x на

DrugB2, DrugB1, DrugB3, DrugA, DrugC1, DrugC2, DrugC3, DrugC4

Я застрял на этом пару часов ... Я ценю любую помощь или идеи.

1 Ответ

2 голосов
/ 05 октября 2019

Проблема не в оси х, у оси х есть только одно значение в каждом фасете. Скорее всего, проблема заключается в упорядочении уровней факторов в пределах file.g$class и file.g$group, которые вы используете для фасетирования. Это не проблема, специфичная для facet_nested, у вас будет та же проблема заказа с facet_grid, на которой она основана.

Следующее возвращает мне заказ, который вы упомянули, вы хотели:

# Reordering factors
file.g$class <- factor(file.g$class, 
                       levels = c("Class B", "Class A", "Class C"))
file.g$group <- factor(file.g$group, 
                       levels = c("98.85%", "98.71%", "87.51%", "93.2%", "96.9%", "98.2%", "99%"))

# Plotting
ggplot(file.g, aes(fill = type, x = drug, 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),
        plot.title = element_text(hjust = 0.5)) +
  facet_nested(.~class + group, scales = "free_x", space= "free_x")

enter image description here

...