Home > Mobile >  ggplot keeping order of dataset on axis
ggplot keeping order of dataset on axis

Time:09-28

I have this dataset that I created a bar graph for using ggplot.However, in my plot, R has the order of the visits ordered incorrectly(see plot below). I want it from visit 1, 2, 3, ......Visit 12. How can I edit my code so that my x-axis labels is in the correct order? I have included by code below

enter image description here

Below is the R code I used to generate the graph.

ggplot(data =data_new %>% gather(values, Score_dose, -Visit), 
   aes(x = Visit, y = Score_dose, fill = values))   geom_bar(stat = 'identity', position = 'dodge') theme_bw()

CodePudding user response:

Fixing the order could always or most of the time be achieved by converting to a factor with the levels set in the desired order. As long as your data is already in your desired order a trick would be to use unique, i.e. do factor(Visit, levels = unique(Visit)). Less error prone would be to set the levels explicitly using e.g. factor(Visit, levels = paste("Visit", 1:12)).

Using some fake example data and the first approach:

data_new <- data.frame(
  Visit = paste("Visit", 1:12),
  Score = 1:12,
  Dose = rev(1:12)
)

library(ggplot2)
library(tidyr)

ggplot(data =data_new %>% gather(values, Score_dose, -Visit), 
       aes(x = factor(Visit, levels = unique(Visit)), 
           y = Score_dose, fill = values))   
  geom_bar(stat = 'identity', position = 'dodge') 
  theme_bw()

  • Related