with a dataframe like below
text <- "
name,miles
tata_zest,99.8
toyota_prius,100.0
honda_civic,99.9
toyota_corolla,100.0
tata_safari,99.1
nissan_sunny,100.0
"
df <- read.table(textConnection(text), sep=",", header = T, stringsAsFactors = F)
I need to have a bar plot for the miles for the various names such that they are sorted in descending order of miles. So I do the following.
df <- df %>%
arrange(desc(miles))
df$name <- factor(df$name, levels = df$name)
ggplot() +
geom_col(data=df, aes(x=name, y=miles) )
This gives me a bar chart like below - nice and great. The bars are sorted in descending order. I want to generate horizontal bar charts with the same data. By adding coord_flip() this could be achieved. However the challenge is that in the horizontal bar charts I want to have the bar with largest value at the top and the smallest value at the bottom.


would something like this work for you? More or less identical to Tino 's comment
df <- arrange(df, miles)
df$name <- factor(df$name, levels = df$name)
ggplot(df, aes(name, miles, fill = name)) + geom_col() + coord_flip() +
scale_fill_brewer(palette="Spectral")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With