Home > Back-end >  EDIT: How to convert to factor variable to order Time data on plot
EDIT: How to convert to factor variable to order Time data on plot

Time:04-11

EDIT ::: I would like the values on the X axis to by in chronological order in AM and PM groups. so 1:00AM - 11:00AM 12:00PM - 9:00PM

I know this has to do with changing my ActivityHoursII variable to a factor. However I am unsure on the steps to do this.

currently: factorintensities <- factor(hourlyIntensitiesclean$ActivityHour) levels(factorintensities) enter image description here

CodePudding user response:

Let df be the name of the data.

METHOD 1

We can specify the order of the axis first.

axisorder <- c("1:00:00 AM","2:00:00 AM","3:00:00 AM","4:00:00 AM","5:00:00 AM","6:00:00 AM","7:00:00 AM", "8:00:00 AM", "9:00:00 AM", "12:00:00 AM")

And then use limits argument in scale_x_discrete function to reorder the axis.

ggplot(data=df)  
  geom_point(mapping = aes(x = ActivityHoursII, y = AverageIntensity))  
  theme(axis.text.x = element_text(angle = 45))  
  scale_x_discrete(limits = axisorder)

METHOD 2

OR, we can change the column into factor and give it levels.

df$ActivityHoursII <- factor(df$ActivityHoursII, levels = axisorder)

And then plot it without scale_x_discrete

ggplot(data=df)  
  geom_point(mapping = aes(x = ActivityHoursII, y = AverageIntensity))  
  theme(axis.text.x = element_text(angle = 45))

And we can get the plot :

desire plot

  • Related