0

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.

d.b
  • 32,245
  • 6
  • 36
  • 77

2 Answers2

0

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")
d.b
  • 32,245
  • 6
  • 36
  • 77
0

This is a good question! But you should got through this How to make a great R reproducible example how to technically ask a question on stackoverflow:

We could use

  1. geom_col instead of geom_bar
  2. reorder + for ascending - for descending:
library(tidyverse)
ggplot(df, aes(x=reorder(name1, +value1), value1))+
  geom_col()

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66