1

I wrote the following function to create some plots:

plot <- function(date, gene, DM) {
 all_concats %>% filter (date_plate_reading == date & gene_name == gene & DM_mm == DM) %>% ggplot(aes(peptide, peptide_reading_total_sem)) + 
    geom_point() + 
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
    labs(x="peptide", y = "Standard mean error") +
    ggtitle(gene, date)
}

the gene_name variable (gene in the function) has the following structure: gene-1, gene-2, gene-3, etc

When I create the plot, the x axis appears in alphabetical order, so gene-1, gene 10, gene 100, etc, instead of gene-1, gene2, ...

How could I reorder the x axis following a numerical order? Thanks!

jrcalabrese
  • 2,184
  • 3
  • 10
  • 30
Sergio
  • 11
  • 2
  • Does this answer your question? [How to sort a character vector where elements contain letters and numbers?](https://stackoverflow.com/questions/17531403/how-to-sort-a-character-vector-where-elements-contain-letters-and-numbers) – Cloudberry Mar 07 '23 at 19:38
  • Try `gtools::mixedsort(example_string, decreasing = TRUE)` where `example_string` is most likely your `all_concats$peptide` variable – jpsmith Mar 07 '23 at 20:14

1 Answers1

0

One option is to turn peptide into a factor with the levels in the desired order. str_sort() from the stringr package with numeric = TRUE can sort the levels in the way you want them.

library(tidyverse)

df <- tibble(
  peptide_id = 1:20,
  peptide = paste("gene", peptide_id, sep = "-")
) %>%
  mutate(
    peptide_reading_total_sem = map(peptide_id, ~rnorm(10, mean = .x))
  ) %>%
  unchop(peptide_reading_total_sem)

ggplot(
  df, aes(peptide, peptide_reading_total_sem)
) +
  geom_jitter() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  labs(x="peptide", y = "Standard mean error")


df_sorted <- df %>%
  mutate(
    peptide = factor(
      peptide,
      levels = str_sort(unique(peptide), numeric = TRUE)
    )
  )

ggplot(
  df_sorted, aes(peptide, peptide_reading_total_sem)
) +
  geom_jitter() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  labs(x="peptide", y = "Standard mean error")

Created on 2023-03-07 with reprex v2.0.2

Clemens Hug
  • 477
  • 4
  • 8