0

I want to use the face_wrap functionality of ggplot to draw the following example data. The plot doesn't seem right. The line should have smooth connection with no extra space in both facets (ie Facet A has empty space from 10-15 while Facet B has space 0-5). Also the months on the x-axis is a bit odd.

library(tidyverse)
library(lubridate)


set.seed(555)

D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                      A = runif(1095, 0,10), Z = runif(1095, 5,15))
D %>% pivot_longer(-Date, names_to = "Variable", values_to = "Value") %>% 
  mutate(Year = year(Date), Month = month(Date)) %>% 
  ggplot(aes(x = Month, y = Value, col = as.factor(Year)))+
  geom_line()+facet_wrap(~Variable, nrow = 2)

enter image description here

Desired Output: I am looking for a plot like below where the lines have smooth month to month connection. enter image description here

Hydro
  • 1,057
  • 12
  • 25
  • You have many data points on each month line because they are not summarized by month in the preceding data frame. – Dealec Jul 17 '20 at 18:23

2 Answers2

1

If you want to use the day of year as your x-position and still get a valid date axis, you could un-year your date:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date


set.seed(555)

D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                A = runif(1095, 0,10), Z = runif(1095, 5,15))
D %>% pivot_longer(-Date, names_to = "Variable", values_to = "Value") %>% 
  mutate(Year = year(Date), Month = month(Date),
         Date = {year(Date) <- 2000; Date}) %>%
  ggplot(aes(x = Date, y = Value, col = as.factor(Year)))+
  geom_line()+facet_wrap(~Variable, nrow = 2) +
  scale_x_date(date_breaks = "1 month", 
               date_labels = "%b")

Created on 2020-07-18 by the reprex package (v0.3.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • Thanks- this looks good. There is quite a bit of space on each ‘facet’ panel. For example, ‘facet A’ has empty space from 10-15. – Hydro Jul 17 '20 at 23:24
  • You can set `scales = "free"` in the `facet_wrap()` function. – teunbrand Jul 18 '20 at 06:41
0

You can try this:

D %>% pivot_longer(-Date, names_to = "Variable", values_to = "Value") %>% 
  mutate(Year = year(Date), Month = month(Date)) %>% 
  ggplot(aes(x = factor(Month), y = Value, col = as.factor(Year),group=factor(Year)))+
  geom_line()+facet_wrap(~Variable, nrow = 2,scales='free')

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • thanks@Duck, the lines still have pretty straight connection between month to month. I just upload a hand drawn `figure` that i am looking to get. – Hydro Jul 17 '20 at 19:14
  • @Hydro I think it depends on your data, are the `rnorm()` values your original variables – Duck Jul 17 '20 at 19:58