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()
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()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments