Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading