如何通过 ggplot2 绘制条形图并按非字母顺序对条形进行排序

How to plot a bar plot by ggplot2 and sort bars in non-alphabetical order

我正在尝试按 ggplot2 绘制箱线图,它按字母顺序对框进行排序,但我想更改它们的顺序。我该怎么做?

感谢您的帮助。

这是我的代码:

mydata <- data.frame(DRG=c(12,23,15,60,2),
                     XPA=c(30,25,55,70,63),
                     SHO=c(22,15,34,23,14),
                     ALA=c(120,95,113,126,103))
row.names(mydata) <- c("sample1","sample2","sample3","sample4","sample5")
mydata <- t(mydata)
mydata <- as.data.frame(mydata)

b.plot <- ggplot(data=mydata, aes(x=row.names(mydata), y=sample1)) +
  geom_bar(stat="identity" , color="green" , fill="yellowgreen", position="dodge" , width = 0.5) +
  xlab("Genes") +
  ylab("Expression") +
  theme(axis.text.x = element_text(size = 10, angle = 45, hjust = 1), 
        plot.margin = margin(0.5,0.5,0.5,2, "cm"))
b.plot

您可以将 x 设置为一个因数,然后使用 levels 设置您想要的顺序。

library(tidyverse)

ggplot(data = mydata, aes(x = factor(
  row.names(mydata),
  levels = c("DRG", "XPA", "SHO", "ALA")
), y = sample1)) +
  geom_bar(
    stat = "identity" ,
    color = "green" ,
    fill = "yellowgreen",
    position = "dodge" ,
    width = 0.5
  ) +
  xlab("Genes") +
  ylab("Expression") +
  theme(
    axis.text.x = element_text(
      size = 10,
      angle = 45,
      hjust = 1
    ),
    plot.margin = margin(0.5, 0.5, 0.5, 2, "cm")
  )

输出

我们可以使用 forcats 包中的 fct_relevel(它在 tidyverse 中)。

  1. 使用 tibble 包中的 rownames_to_column 函数(在 tidyverse 中)

    将您的行名添加到列 gene
  2. 使用fct_relevel随意设置顺序

  3. 然后用ggplot2(我用的是geom_col()

library(tidyverse)

mydata %>% 
  rownames_to_column("gene") %>% 
  pivot_longer(
    cols = -gene
  ) %>% 
  mutate(gene = fct_relevel(gene, 
                            "SHO", "DRG", "ALA", "XPA")) %>% 
  ggplot(aes(x=gene, y=value))+
  geom_col(color="green" , fill="yellowgreen", position="dodge" , width = 0.5)+
  xlab("Genes")+
  ylab("Expression") +
  theme(axis.text.x = element_text(size = 10, angle = 45, hjust = 1), 
        plot.margin = margin(0.5,0.5,0.5,2, "cm"))