Natha
Natha

Reputation: 384

Reorder labels in ggplot based on values in 2 colums

I would like to build a bar plot in R in which the labels in x axis are ordered by the value in Count if Name == A. When I build it, it simply order the x axis "Tool 1, Tool 2, Tool 3". What I would like is to get a x axis order like "Tool 3, Tool 1, Tool 2" (ordering by values in Name == A).

Here is a tiny dataframe as example:

df <- rbind(tibble(Name = c('A', 'B', 'C'), Count = c(6, 3, 1), Method = rep('Tool 1', 3)),
        tibble(Name = c('A', 'B', 'C'), Count = c(4, 2, 4), Method = rep('Tool 2', 3)),
        tibble(Name = c('A', 'B', 'C'), Count = c(7, 3, 0), Method = rep('Tool 3', 3))
        )
df

# A tibble: 9 x 3
  Name  Count Method
  <fct> <dbl> <chr> 
1 A         6 Tool 1
2 B         3 Tool 1
3 C         1 Tool 1
4 A         4 Tool 2
5 B         2 Tool 2
6 C         4 Tool 2
7 A         7 Tool 3
8 B         3 Tool 3
9 C         0 Tool 3

To build the plot:

p <- ggplot(df, aes(x = Method,
                       y = Count,
                       fill = Name)) +
  geom_bar(stat="identity")

p

enter image description here

I tried to rearrange it with df %>% mutate(Method = fct_reorder(Method, desc(Count))) but I don't know how to select only by A values. I also could reorder it manually but I am interested in knowing how to do it automatically. Thanks for the help !

Upvotes: 1

Views: 170

Answers (2)

bouncyball
bouncyball

Reputation: 10761

We can add a column to df and use the reorder function

df$Count_A <- ifelse(df$Name == "A", df$Count, NA)

ggplot(df, aes(x = reorder(Method, -Count_A, mean, na.rm = TRUE),
               y = Count,
               fill = Name))+
  geom_bar(stat="identity")

enter image description here

Alternatively, you could add the reordered factor to df:

df$Method <- reorder(df$Method, -df$Count_A, mean, na.rm = TRUE)

ggplot(df, aes(x = Method, y = Count, fill = Name)) +
  geom_bar(stat="identity")

Upvotes: 1

jay.sf
jay.sf

Reputation: 72593

Using relevel.

p <- ggplot(transform(df, Method=relevel(as.factor(Method), ref="Tool 3")), 
            aes(x = Method,y = Count, fill = Name)) +
  geom_bar(stat="identity")
p

Upvotes: 1

Related Questions