Reputation: 5069
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 name
s 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.
Upvotes: 3
Views: 7892
Reputation: 7958
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")
Upvotes: 3