Home > database >  geom_bar() with sorted values
geom_bar() with sorted values

Time:10-14

I have following data.

df <- data.frame(name1 = c("Chi", "Ron", "Gen", "Ral", "Cha", "Det", "Har", "Was"),
                 value1 = c(641, 548, 459, 367, 366, 324, 317, 309))

I want to create a bar plot to visualize this data. The bars should be in increasing or decreasing order of values each with different color. The legend should show which color belongs to which name. How do I do it using geom_bar() function.

CodePudding user response:

convert name1 to factor and set levels by ordering name1 based on value1

df$name1 = factor(df$name1, df$name1[order(df$value1)])
ggplot(df[order(df$value1),], aes(x = name1, y=value1, fill = name1))  
    geom_bar(stat = "identity")

CodePudding user response:

This is a good question! But you should got through this enter image description here

  • Related