ggplot scatter plot secondary grouping / sorting by date

Hello R Studio Community!

I have data where I want to plot in the x-direction by 2 variables -- SN (serial number) and date.

When I plot with date on the x-axis all is well, and SN on the X-axis displays in groups like I want:
image

except the groups of points in the 2nd plot use position=position_jitter(seed=42) which is random, and what I need is for the groups of points in the SN plot to displayed in date order.

Is there a way to get secondary sorting/grouping? That is, the 2nd plot, except with the points displayed in time order instead of randomly jittered?

My plotting code looks like this: (note that "color=" doesn't work, I haven't cracked that yet either)

  p<-ggplot(ds_filtered,  
    aes_string(
      x 		= plot.obj$xVar,
      y 		= plot.obj$yVar,
      color = factor(ds_filtered$Run) # let type determine plotting
    )) 
  
  p<-p+ geom_point(color='blue',alpha=0.5, position=position_jitter(seed=42)) + 
    geom_hline(yintercept=usl, color="red") + 
    geom_hline(yintercept=lsl, color="green") +
    scale_x_discrete(guide = guide_axis(check.overlap = TRUE))+
    theme(axis.text.x = element_text(angle=90))

Thank you very kindly!
Andy

Without having your data, I can't check my ideas but here are some suggestions.
It seems the date-time values are characters, not numeric values. I would make those numeric using the mdy_hm() function from lubridate.
I would plot date on the x axis and use facet_wrap(~ SN, nrow = 1) to get a subplot for each SN value with all of the plots on one row.
You set color = "blue" in geom_point and that is probably overriding color = factor(ds_filtered$Run) in the aes() of ggplot().

1 Like

Yes, that worked great. facet_wrap is what I needed, and your other comments solved my other issues. Thank you very kindly!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.