Home > database >  R: how to layer two facet ggplot from two different df with dates as the x axis?
R: how to layer two facet ggplot from two different df with dates as the x axis?

Time:09-16

I would like to combine these two ggplots: origin from different data frames with the same X axis (floor_dates) and same facet_wrap. The two plots:

ggplot(averaged_activity,aes(x=date(DATETIME),y=PERCENTAGE), group = POPULATION)  
    geom_line(stat = "summary", fun = "mean")  geom_point(stat = "summary", fun = "mean") 
    labs(y="Activity (%)", x = "Date") 
    scale_x_date(date_labels="%d/%m/%y",date_breaks  ="1 week") 
    scale_y_continuous() 
    facet_wrap(~POPULATION, ncol=1)

looks like: enter image description here and

ggplot(info_table, aes(x=floor_date(DATE_OF_METAMORPHOSIS, unit = "week"), group= POPULATION)) 
  geom_histogram() facet_wrap(~POPULATION, ncol=1)

looks like: enter image description here I would like the two plots to be combined on the same graph.

I've tried to add the histogram to the first ggplot with geom_histogram(info_table, aes(x=floor_date(DATE_OF_METAMORPHOSIS, unit = "week"), group= POPULATION)), I also tried to create the ggplot with no defined data frame and define the data frames inside the geoms. but every way I tried I got a different error, all about r having trouble finding variables, like the "POPULATION" variable in the facet or the group commend or the "PERCENTAGE" variable in the y axis.

tnx!

CodePudding user response:

Here is an option of pulling the two graph together. (As per comments, it would be best to include enter image description here

Merging the plots together


One option to merge the plot is to call for data= and aes() in each geom_. Plus one issue here is that the histogram count is around 10 max whereas the lines could be in the hundreds. The trick is to multiply the y = stat(count) here by 10 to have them overlay the points. Then in the scale_y_continuous() you can call for the second axis and do the inverse transformation. In our case dividing by 10 sec.axis = sec_axis(~ . / 10, name = "Count")

ggplot() 
  geom_histogram(data=df2, aes(x=floor_date(DATE_OF, unit= "week"), y = stat(count)*10), binwidth = 10) 
  geom_line(data=df1, aes(x=DATETIME, y=percentage), stat = "summary", fun = "mean") 
  geom_point(data=df1, aes(x=DATETIME, y=percentage), stat = "summary", fun = "mean") 
  scale_y_continuous("Percentage (%)", sec.axis = sec_axis(~ . / 10, name = "Count")) 
  facet_wrap(~surname, ncol=1) 
  labs(x="Date")

enter image description here

  • Related