1
votes

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)

1
There should be a column named BC04 in the datasetakrun

1 Answers

0
votes

Earlier, strings passed to ggplot, are evaluated with aes_string (which is now deprecated). Now, we convert the string to symbol 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 descending 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

enter image description here


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')