Search code examples
rggplot2facet

How to make continuous plots with line/block separations in ggplot2


I have melted data frame contains Msrt_Order, Sample_Intensity, rtc, Group and Msrt_Day.

I want to make a plot of Sample Intensity peak along the Msrt_Order (measurement order, from 1 to 1000+)

ggplot(peak) +  geom_jitter(aes(x = Msrt_Order, y = Sample_Intensity, color = rtc, shape=rtc), alpha = 0.6)

enter image description here

I want to make it better by separating them according to the msrt_Day (measurement_day, an order along with Msrt_Order, but instead of 1000+ factors, there are only 24 days as we measure 40+ samples per day.)

What I DON'T want is this

ggplot(peak) +  geom_jitter(aes(x = Msrt_Order, y = Sample_Intensity, color = Msrt_Day, shape=rtc), alpha = 0.6)

enter image description here

because there are 24 of them, it's hard to distinguish, nor do I want 24 icons in the legend.

I tried to use facet_grid

ggplot(peak) +  geom_jitter(aes(x = Msrt_Order, y = Sample_Intensity, color = rtc, shape=rtc), alpha = 0.6) + facet_grid(~Msrt_Day)

enter image description here But it's NOT what I expected, I want to have a continuous plot with 24 blocks separated by Mrst_Day while maintaining the Msrt_Order.

Hope you guys get my idea...

The peak csv link is here peak.csv


Solution

  • I think what you want to do is add one or more variables which describe the boundaries of Msrt_Day using the x-axis values Msrt_Order.

    Here's one attempt: group by Msrt_Day and define the boundary as the maximum value of Msrt_Order for each group. Then you can use that value for geom_vline.

    peak %>% 
      group_by(Msrt_Day) %>% 
      mutate(orderMax = max(Msrt_Order) %>% 
      ungroup() %>% 
      ggplot(aes(Msrt_Order, Sample_Intensity)) + 
      geom_point(aes(color = rtc)) + 
      geom_vline(aes(xintercept = orderMax)) +
      theme_bw()
    

    Result:

    enter image description here