【问题标题】:ggplot using facet_wrap of multiple data.frame with different length in R?ggplot在R中使用不同长度的多个data.frame的facet_wrap?
【发布时间】:2020-11-09 20:59:45
【问题描述】:

我正在尝试使用下面的代码实现附加的手绘图,但它显示了我没有数据的所有年份的空白。任何帮助将不胜感激。

library(lubridate)
library(tidyverse)

set.seed(123)

D1 <- data.frame(Date = seq(as.Date("2001-07-14"), to= as.Date("2001-07-21"), by="day"),
           A = runif(8, 0,10),
           D = runif(8,5,15)) %>% 
    gather(-Date, key = "Variable", value = "Value")

D2 <- data.frame(Date = seq(as.Date("1998-07-14"), to= as.Date("1998-08-30"), by="day"),
                 A = runif(48, 0,10),
                 D = runif(48,5,15)) %>% 
    gather(-Date, key = "Variable", value = "Value")

D <- bind_rows(D1,D2) %>% mutate(Year = year(Date))

my_linetype <- setNames(c("dashed", "solid"), unique(D$Year))

ggplot(data = D, aes(x = Date, y = Value, color = as.factor(Year), linetype = as.factor(Year)))+
  geom_line(size = 1.1)+ facet_wrap(~Variable,  scales = "free_y", nrow=2)

想要的结果

【问题讨论】:

    标签: r dataframe ggplot2 tidyverse facet-wrap


    【解决方案1】:

    您可以在 data.frame 中创建一个虚拟的 Date 变量,其中不同组的年份相同。在下面的示例中,在Unyear 变量下的mutate() 语句中添加了这一点。

    D <- bind_rows(D1,D2) %>% mutate(Year = year(Date),
                                     Unyear = {year(Date) <- 0; Date})
    
    my_linetype <- setNames(c("dashed", "solid"), unique(D$Year))
    
    ggplot(data = D, aes(x = Unyear, y = Value, color = as.factor(Year), linetype = as.factor(Year)))+
      geom_line(size = 1.1)+ facet_wrap(~Variable,  scales = "free_y", nrow=2)
    

    【讨论】:

    • 感谢@teunbrand,我尝试使用scale_x_date(limits = as.Date(c("0000-07-11","0000-08-30")), expand = c(0, 0), date_breaks = "1 week"),但这给了我以0000 开头的轴。有什么方法可以进一步break x-axis 而不是只有4个默认breaks
    • 是的,这似乎是意料之中的。您可以在该函数中使用 date_labels = "%d-%m" 从标签中省略年份。
    猜你喜欢
    • 2020-11-05
    • 2016-03-12
    • 2020-07-02
    • 2017-01-17
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多