简体   繁体   中英

Mantain order of dataframe for a stacked barplot using ggplot2

Using the following dataframe and ggplot...

sample ="BC04"
df<- data.frame(Name=c("Pseudomonas veronii", "Pseudomonas stutzeri", "Janthinobacterium lividum", "Pseudomonas viridiflava"),
                 Abundance=c(7.17, 4.72, 3.44, 3.33))

ggplot(data=df, aes(x=sample, y=Abundance, fill=Name)) +
  geom_bar(stat="identity")

... creates the following graph

barplot

Altough the "geom_bar(stat="identity")" is set to "identity", it still ignores the order in the dataframe. I would like to get a stack order based on the Abundance percentage ( Highest percentage at the top with ascending order )

Earlier, strings passed to ggplot , are evaluated with aes_string (which is now deprecated). Now, we convert the string to sym bol and evaluate ( !! )

library(ggplot2)
ggplot(data=df, aes(x= !! rlang::sym(sample), y=Abundance, fill=Name)) +
  geom_bar(stat="identity")

Or another option is .data

ggplot(data=df, aes(x= .data[[sample]]), y=Abundance, fill=Name)) +
  geom_bar(stat="identity")

Update

By checking the plot, it may be that the OP created a column named 'sample. In that case, we reorder the 'Name' based on the desc ending order of 'Abundance'

df$sample <- "BC04"
ggplot(data = df, aes(x = sample,  y = Abundance, 
  fill = reorder(Name, desc(Abundance)))) + 
       geom_bar(stat = 'identity')+ 
       guides(fill = guide_legend(title = "Name"))

-output

在此处输入图像描述


Or another option is to convert the 'Name' to factor with levels mentioned as the unique elements of 'Name' (as the data is already arranged in descending order of 'Abundance')

library(dplyr)
df %>%
  mutate(Name = factor(Name, levels = unique(Name))) %>% 
  ggplot(aes(x = sample, y = Abundance, fill = Name)) +
     geom_bar(stat = 'identity')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM