0
$\begingroup$

Good afternoon,

I am trying for a while now to wrap these labels in my plot (I want that it goes to the next line instead of making a very long line). I tried with the scales package in R, but it seems not to work.. Any chance someone can advise me on this?

p<-ggplot(fgseaResTidy, aes(reorder(topPathways, NES), NES)) +  
geom_col(aes(fill=padj<0.05)) +   coord_flip() +   labs(x="Pathway",
y="Normalized Enrichment Score") +   theme_minimal()

p + scale_x_discrete(
    labels = function(x) str_wrap(x, width = 10),
    drop = FALSE   )

enter image description here

Update

Trying with code recommendation from answer below:

enter image description here

$\endgroup$
2
  • 1
    $\begingroup$ How would one break where to wrap? As far as the program knows, there is no white space to break at even if things allowed for wrapping to happen. Also, font size would go down when wrapped, or rows with wrapping would get larger. Which of these do you expect? $\endgroup$
    – Ram RS
    Commented Oct 18 at 19:25
  • 1
    $\begingroup$ Ahh ok! now I got it. I added this line and now it works!! fgseaResTidy$pathway=str_replace_all(fgseaResTidy$pathway, "_", " ") $\endgroup$
    – Bine
    Commented Oct 20 at 9:31

1 Answer 1

2
$\begingroup$

I googled "ggplot2 labels break" and this was the second link: https://www.andrewheiss.com/blog/2022/06/23/long-labels-ggplot/

It shows how exactly to do this, something like this after you introduce line breaks:

p <- ggplot(fgseaResTidy,
        aes(reorder(topPathways, NES), NES)) +  
        geom_col(aes(fill=padj<0.05)) + 
        coord_flip() + 
        labs(x="Pathway", y="Normalized Enrichment Score") +
        theme_minimal()

p + scale_x_discrete(
            labels = label_wrap(100))
$\endgroup$
3
  • $\begingroup$ Thank you for your answer. I also saw this post and I actually tried it from there. But it seems I am doing something wrong, nothing is changing. See picture added to post above. $\endgroup$
    – Bine
    Commented Oct 19 at 15:55
  • 1
    $\begingroup$ @Bine How did you introduce line breaks into the label names? You need to do that first, as Ram RS notes above. And please, post code as text, not pictures. $\endgroup$
    – Cloudberry
    Commented Oct 19 at 18:53
  • $\begingroup$ Got it, issue was the "_" :) $\endgroup$
    – Bine
    Commented Oct 20 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.