R语言 如何对ggplot 2图进行重新排序,以便按不同的字符向量/列对字符列进行分组?

wkyowqbh  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一组患者样本,我有基因表达数据。我想创建一个条形图,其中x轴是单个样本,y轴是给定基因的计数,填充是患者的诊断。然后,我希望显示数据,以便将诊断标绘/分组在一起(无分面)。
想象一下mtcars,其中行名称存储为按字母顺序分解的“car”列,并且还有一个单独的“car_model”列。绘制的X轴特征在于针对其重量绘制的每个汽车,然后将通过car_model来布置/分组。

p <- ggplot(mtcars, aes(x= car, y= wt, fill= car_model)) + 
    geom_bar(stat = 'identity') +  theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
    xlab('car')+ ylab('wt')+
    ggtitle(cars)
  print(p)

我已经尝试/查看了factor/level,fct_reorder/2,order/reordering the data,str_sort,arrange,grouping...在ggplot 2代码的内部和外部。我以为下面的代码(或ggplot代码中的fct_reorder/2)可以工作,但它没有:

mtcars$car_model <- relevel(mtcars$car_model, "Toyota") #Reorder group so that the Toyota group is specifically first and everything else remains as it was

mtcars <- mtcars[order(mtcars$car, mtcars$car_model),] # Then plot

我已经考虑过将car_model列变异为一个数值向量,并试图以这种方式排序,但我也认为我错过了一些愚蠢的显而易见的东西。请给我小费。
谢谢!

mrfwxfqh

mrfwxfqh1#

一个最小的可重复的例子可以帮助社区理解你的问题。无论哪种方式,我猜你正在寻找这样的东西:

library(ggplot2)

# Create a sample dataset
gene_data <- data.frame(
  sample = c("Sample1", "Sample2", "Sample3", "Sample4", "Sample5", 
             "Sample6"),
  gene_count = c(10, 15, 8, 12, 9, 11),
  diagnosis = c("Diagnosis1", "Diagnosis2", "Diagnosis2", "Diagnosis1", 
                "Diagnosis3", "Diagnosis1")
)

# Reorder the levels of the diagnosis factor to match the desired grouping order
gene_data$diagnosis <- factor(gene_data$diagnosis, 
                       levels = c("Diagnosis1", "Diagnosis2", "Diagnosis3"))

# Create the bar chart
p <- ggplot(gene_data, aes(x = sample, y = gene_count, fill = diagnosis)) +
  geom_bar(stat = 'identity') +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  xlab('Sample') +
  ylab('Gene Count') +
  ggtitle('Gene Expression by Diagnosis')

# Group the samples by diagnosis using the 'sample' column
p <- p + scale_x_discrete(limits = 
              unique(gene_data$sample[order(gene_data$diagnosis)]))

p

相关问题