Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot - horizontal bar plot sort with largest at top

Tags:

r

ggplot2

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.

enter image description here

enter image description here

like image 411
user3206440 Avatar asked May 28 '26 02:05

user3206440


1 Answers

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

plot

like image 153
Eric Fail Avatar answered May 31 '26 06:05

Eric Fail



Donate For Us

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