Naomi Croft Guslund
Naomi Croft Guslund

Reputation: 1

ggplot2: Remove first word of axis label

When I run this script I get the following plot:

ggplot(fgseaResTidy %>% filter(padj < 0.05) %>% head(n= 20), aes(reorder(pathway, NES), NES)) +
  geom_col(aes(fill= NES > 5)) +
  coord_flip() +
  labs(x="Pathway", y="Normalized Enrichment Score",
       title="Hallmark pathways NES from GSEA") + 
      theme(axis.text.y.left = element_text(size = 10)) +
      scale_x_discrete(label = function(x) stringr::str_trunc(x, 40, "right"))
  theme_minimal()

enter image description here

I have tried truncating the scale_x_discrete labels to shorten the labels, but I want to remove the "REACTOME_" part which is at the front of each label. Any suggestions?

Thanks for your time! Naomi

Upvotes: 0

Views: 498

Answers (1)

MrGumble
MrGumble

Reputation: 5776

This is not (neccesarily) an issue with ggplot but simple data-manipulation prior to calling ggplot.

1st, try moving your data.frame manipulation outside of ggplot:

fgseaResTidy %>% filter(padj < 0.05) %>% head(n= 20) %>%
ggplot(aes(reorder(pathway, NES), NES)) +
  geom_col(aes(fill= NES > 5)) +
  ...

(it simply improves readability)

Next, do a search and replace on REACTOME_:

fgseaResTidy %>% filter(padj < 0.05) %>% head(n= 20) %>%
mutate(pathway = sub("REACTOME_", "", pathway, fixed=TRUE)) %>%
ggplot(aes(reorder(pathway, NES), NES)) +
  geom_col(aes(fill= NES > 5)) +
  ...

Depending on whether REACTOME_ appears other places in the pathway name, you might want to use regular expressions in sub, i.e. sub("^REACTOME\\_", "", pathway).

Edit:

Well, strictly speaking you could also just remove the text in your call to scale_x_discrete:

scale_x_discrete(label = function(x) {
  x %>% sub("REACTOME_", "", .) %>% stringr::str_trunc(40, "right"))
})

Upvotes: 2

Related Questions