简体   繁体   English

ggplot 在 R 中使用 facet_wrap?

[英]ggplot using facet_wrap in R?

I want to use the face_wrap functionality of ggplot to draw the following example data.我想使用ggplotface_wrap功能绘制以下示例数据。 The plot doesn't seem right. plot好像不对。 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).line应该平滑连接,两个facets都没有多余的空间(即Facet A有 10-15 的空白空间,而Facet B有 0-5 的空间)。 Also the months on the x-axis is a bit odd. x 轴上的月份也有点奇怪。

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.所需的 Output:我正在寻找如下所示的 plot,其中线路每月连接顺畅。 在此处输入图像描述

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:如果你想使用一年中的某一天作为你的 x 位置并且仍然得到一个有效的日期轴,你可以取消你的日期:

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)reprex package (v0.3.0) 创建于 2020-07-18

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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