1

I have a dataframe, that I want to use to plot a bar plot. The numeric variable is jumbled and I sorted it into descedning order. I want to plot the new sorted dataframe using ggplot but the barplot is not giving me the desired output.

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)

df <- data.frame(Name, Age)

print (df)
  Name Age
1   Jon  23
2  Bill  41
3 Maria  32
4   Ben  58
5  Tina  26

#sort in descending order
df2<-df%>%
  arrange(desc(Age))
print(df2)

The outcome is below:
 Name Age
1   Ben  58
2  Bill  41
3 Maria  32
4  Tina  26
5   Jon  23

To plot it my attempt is below. But now it does not plot them in the descending manner I was expecting.

#plot it using gglot
df2%>%ggplot(aes(x=Name, y=Age)) +
  geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
  coord_flip() +
  xlab("") +
  theme_bw()

this the output it gives me: enter image description here

thole
  • 117
  • 6

2 Answers2

4

you can use reorder function from the stats package in the x aesthetic mappings

library(dplyr)
library(ggplot2)

df%>%ggplot(aes(x=reorder(Name,Age), y=Age)) +
  geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
  coord_flip() +
  xlab("") +
  theme_bw()

Created on 2023-04-12 with reprex v2.0.2

Wael
  • 1,640
  • 1
  • 9
  • 20
1

To plot a character vector in an order other than alphabetical you turn it into a factor. Either factoring after ordering or using the forcats:fct_reorder function to do both at the same time would work:

library(ggplot2)

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)

df <- data.frame(Name, Age)

# Reorder using -Age (to order descending)

df |> ggplot(aes(x=forcats::fct_reorder(Name, -Age), y=Age)) +
  geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
  coord_flip() +
  xlab("") +
  theme_bw()

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22