Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to plot a barplot using ggplot2

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading