Setting the order of x or y in ggplot by row index (original order of the data) and not by alphabetical order

I want to plot my data based on their original order and not by alphabetical or numerical order (the order from top to bottom should be like variable d, variable a, variable c and variable b). My df is like below one:

df <- tribble(
  ~variables, ~names, ~values,
  'vard', "D", 2.5,
  'vard', "D", 3.5,
  'vard', "D", 4.9,
  'vara', "A", 2.5,
  'vara', "A", 3.5,
  'vara', "A", 4.9,
  'varc', "C", 8.5,
  'varc', "C", 7.3,
  'varc', "C", 6.1,
  'varb', "B", 3.1,
  'varb', "B", 5.2,
  'varb', "B", 7.8,
  
)
df %>% ggplot( aes(x=variables, y=values)) + coord_flip()

enter image description here

>Solution :

Try this:

new_levels <- df$variables %>% unique %>% rev
df <- df %>% mutate(variables = factor(variables, levels = new_levels))
df %>% ggplot( aes(x=variables, y=values)) + coord_flip()

enter image description here

Leave a Reply