0

When I run this and the plot comes up, the order of my x axis labels (column titles) get rearranged. How do i maintain the order that i created in the df?

Here is my dataset and code, with values hidden:

library(tidyverse)
library(cowplot)
df <- structure(list(Number_Behavior_1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_2 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_3 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_4 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_5 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_6 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_7 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_8 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_9 = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                     Number_Behavior_10 = c(1, 2, 3, 4, 5, 6, 7, 8, 9)),
                            class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L))
df_Number <- df %>% 
  pivot_longer(
    cols = 1:10,
    names_to = "names",
    values_to = "values"
  ) %>% 
  filter(grepl('Number', names))

plot_Number <- ggplot(df_Number, aes(x=factor(names), y=values)) +
  geom_point(stat = "identity") + 
  geom_smooth(method = 'lm', formula = y~x)+
  xlab("Number") + 
  ylab("Value") +
  theme_bw()

plot_grid(plot_Number, labels = "AUTO")
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Ryan Bruno
  • 321
  • 1
  • 8
  • 1
    Does this answer your question? [Order Bars in ggplot2 bar graph](https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph) – neuroandstats Aug 06 '21 at 17:20
  • Please share your data in a reproducible format. Code like `c(#, #, #, #, #, #, #, #, #)` is not valid R code so we can't copy/paste it into R for testing. Maybe using `aes(x=forcats::fct_inorder(names), y=values)` will do what you want. Hard to say since we can't run to code to see what it currently does. – MrFlick Aug 06 '21 at 17:21
  • fair enough. I edited it – Ryan Bruno Aug 06 '21 at 17:33
  • Did you try `aes(x=forcats::fct_inorder(names), y=values)` as suggested? Because it works when tested with the sample data. The duplicate says bar graph in the title, but the same ordering applies to all ggplot2 graphs with discrete scales. Character values are converted to factors and the order of the factor levels is the order they are drawn. To change the order, you need to change the factor level order. – MrFlick Aug 06 '21 at 17:53

0 Answers0