How to sort x Bar chart by value based on Y

Question : how can i sort the X bar chart based on Y value

i tried the following syntax but it didn't work with me :

ggplot(mpg,aes(manufacturer,fct_reorder(manufacturer,hwy)))+geom_bar(stat = "identity")+coord_flip()

thank you so much

The mpg data set is not the best to use for this example because it has may values of hwy for each manufacturer. I summarized the data to calculate the average value of hwy for each manufacturer and then reordered manufacturer based on that.

library(dplyr)

library(ggplot2)
mpg |> group_by(manufacturer) |> 
  summarize(Avg = mean(hwy)) |> 
  mutate(manufacturer = forcats::fct_reorder(manufacturer, Avg)) |> 
ggplot(aes(manufacturer, Avg)) +
  geom_bar(stat = "identity")+coord_flip()

Created on 2022-07-26 by the reprex package (v2.0.1)

2 Likes

Thank you for this hint , it was really useful , but am wondering is their another way to keep the ordering based on the hwy , which was in the first chart .

thanks again .

I am not sure what you mean by "another way to keep the ordering based on the hwy". In the original mpg data set there are, for example, 18 entries with manufacturer = audi. If you plot

ggplot(mpg,aes(manufacturer,hwy))+
geom_bar(stat = "identity")+coord_flip()

the audi bar will have those 18 hwy values stacked on top of each other. If you want that plot to show the manufacturers ordered with respect to the sum of hwy, you can do

mpg <- mpg |> mutate(manufacturer= fct_reorder(manufacturer, hwy, sum))
ggplot(mpg,aes(manufacturer,hwy))+
  geom_bar(stat = "identity")+coord_flip()

this what i was looking for ..the output now showing the real sum of hwy . as now its showing Toyota the highest value . ,,but its still not sorted

mpg <- mpg |> mutate(manufacturer= fct_reorder(manufacturer, hwy, sum))
ggplot(mpg,aes(manufacturer,hwy))+
geom_bar(stat = "identity")+coord_flip()

after i run the I got the following chart :

thank you for your help and support

Here is what I get. I cannot explain the difference at the moment.

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(forcats)

mpg <- mpg |> mutate(manufacturer= fct_reorder(manufacturer, hwy, sum))
ggplot(mpg,aes(manufacturer,hwy))+
  geom_bar(stat = "identity")+coord_flip()

Created on 2022-07-27 by the reprex package (v2.0.1)

1 Like

Thank you so much for all your help and support ,, I closed R and reopened it then the syntax which you provided me is working fine .

thank you for the help :wink: :wink:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.