Ordering legend the same way data is ordered in donut plot

32 views
Skip to first unread message

thbt.m...@gmail.com

unread,
Oct 18, 2017, 12:21:29 PM10/18/17
to ggplot2
Hi,

I'm starting using ggplot and I have a problem to order the legend the same way data is ordered in the donut plot I'm trying to generate.

I saw similar questions on the forum but unfortunately answers did not help me.

Here is my code:

abundances <- c(11.42, 8.71, 8.36, 6.72, 6.46, 5.24, 5.24, 3.13, 2.48, 2.22, 40.02)
microbes   <- c("Bacteroides vulgatus", "Bacteroides uniformis", "Bacteroides fragilis", "Bacteroides eggerthii", "[Eubacterium] eligens", "Bacteroides cellulosilyticus", 
                "Faecalibacterium prausnitzii", "Bacteroides intestinalis", "Roseburia intestinalis", "Bacteroides salyersiae", "Other organisms")  

dat <- data.frame(abundances=abundances, microbes=microbes, stringsAsFactors=FALSE) 
dat = dat[order(dat$abundances), ]      # order dataframe by abundances
dat$ymax  = cumsum(dat$abundances)      # create ymax column (similar to abundances)
dat$ymin  = c(0, head(dat$ymax, n=-1))  # create ymin column (f)
dat$ymean = (dat$ymin + dat$ymax) / 2

# Make the plot
p1 = ggplot(dat, aes(fill=microbes, xmin=3, xmax=4, ymin=ymin, ymax=ymax)) + 
    geom_rect(colour="grey30") +
    xlim(c(0, 4)) +
    geom_text(data=dat, aes(x=3.5, y=ymean, label=abundances), size=3) +
    coord_polar(theta="y") +                      # to obtain ring plot
    theme_bw() +                                  # ggplot theme
    theme(  panel.grid=element_blank()) +         # to hide grid
    theme(   axis.text=element_blank()) +         # to hide axis text
    theme(axis.title.x=element_blank()) +         # to hide x axis title
    theme(axis.title.y=element_blank()) +         # to hide y axis title
    theme(  axis.ticks=element_blank()) +         # to hide axis ticks
    labs(title="Top10 microbes") +                # title
    scale_fill_discrete(name = "Microbes") +      # Change legend title
    theme(plot.title = element_text(hjust = 0.5)) # Center plot title
p1


As you can see, organism in the legend are ordered alphabetically and not based on their abundances like on the donut plot.

Do you have an idea to order the legend the same way the abundances are?

Or maybe do you have an idea to generate differently a similar donut plot?

Thank you in advance for your answers!

Best,
Thibaut



Pete St Marie

unread,
Oct 18, 2017, 6:26:02 PM10/18/17
to ggplot2
Using the forcats package, you might try using fct_reorder().

For instance, p1 = ggplot(dat, aes(fill=fct_reorder(microbes, abundances), xmin=3, xmax=4, ymin=ymin, ymax=ymax))

--pete

thbt.m...@gmail.com

unread,
Oct 19, 2017, 10:41:21 AM10/19/17
to ggplot2
A HUGE THANK YOU!

Thibaut
Reply all
Reply to author
Forward
0 new messages