简体   繁体   中英

ggplot using facet_wrap in R?

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)

在此处输入图像描述

Desired Output: I am looking for a plot like below where the lines have smooth month to month connection. 在此处输入图像描述

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)

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')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM