Home > Back-end >  Graph facet graph with two sets of data - multivariable (original dataset combines two dataset)
Graph facet graph with two sets of data - multivariable (original dataset combines two dataset)

Time:09-03

I have been trying to find some resources similar to this, but my current dataset looks like this:

lwg_date bon_date lwg_length bon_length
March April 1 31
March April 10 14
March April 12 12
March May 19 11
April May 5 17
April May 19 41
April June 55 24
April June 13 22
August Sept 21 17
August Sept 15 18

I previously had thought that rearranging the dataset would help me create facet graphs but later realized that it would still be quite difficult, and I am having a hard time imagining it now too.

The end result should be graphs based on months (ie. March graph, April graph, May graph) where each graph has two histograms (LWG, BON) overlaying an x-axis of length and y-axis of the count of the respective lwg/bon data.

The issue I kept encountering was understanding how to facet wrap it by months. Perhaps I been going about in circles with this but I have tried reorganizing lwg_month and bon_month column together (which got messy), add both variables in facet wrap (got confused).

I would be open to suggestions; thank you in advance.

CodePudding user response:

library(tidyverse)
data.frame(
  stringsAsFactors = FALSE,
          lwg_date = c("March","March","March",
                       "March","April","April","April","April","August",
                       "August"),
          bon_date = c("April","April","April",
                       "May","May","May","June","June","Sept","Sept"),
        lwg_length = c(1L, 10L, 12L, 19L, 5L, 19L, 55L, 13L, 21L, 15L),
        bon_length = c(31L, 14L, 12L, 11L, 17L, 41L, 24L, 22L, 17L, 18L)
) %>%

  # reshape into    type | date | length
  pivot_longer(everything(), names_to = c("type", ".value"), names_sep = "_") %>%

  # turn date into ordered factor
  mutate(date = ifelse(date == "Sept", "September", date),
         date = factor(date, levels = month.name)) %>%

  # plot histograms
  ggplot(aes(length, fill = type))  
  geom_histogram(bins = 5)  
  facet_wrap(~date)
  • Related