我认为最好逐行绑定两个数据帧(在每个用列标记以声明它所在的原始数据帧之后),然后将它们转换为长格式,以便所有 CW 值都在单列,有一个新列来标记它们来自哪个“CW”。这个新数据框将包含您在ggplot2 中创建简单线图所需的所有信息
library(ggplot2)
library(dplyr)
library(tidyr)
bind_rows(list(sales = sales, forecast = forecast), .id = "type") %>%
pivot_longer(cols = starts_with("CW")) %>%
ggplot(aes(name, value, color = type, group = type)) +
geom_line() +
scale_color_discrete(name = "") +
facet_wrap(.~Product, ncol = 2)
数据
forecast <- structure(list(Product = c("A", "B", "C", "D"), CW1 = c(9L, 7L,
10L, 10L), CW2 = c(12L, 5L, 10L, 9L), CW3 = c(21L, 6L, 20L, 8L
), CW4 = c(8L, 9L, 15L, 8L)), class = "data.frame", row.names = c(NA,
-4L))
sales <- structure(list(Product = c("A", "B", "C", "D"), CW1 = c(10L,
10L, 9L, 10L), CW2 = c(11L, 5L, 10L, 10L), CW3 = c(21L, 7L, 21L,
9L), CW4 = c(7L, 9L, 15L, 8L)), class = "data.frame", row.names = c(NA,
-4L))
forecast
#> Product CW1 CW2 CW3 CW4
#> 1 A 9 12 21 8
#> 2 B 7 5 6 9
#> 3 C 10 10 20 15
#> 4 D 10 9 8 8
sales
#> Product CW1 CW2 CW3 CW4
#> 1 A 10 11 21 7
#> 2 B 10 5 7 9
#> 3 C 9 10 21 15
#> 4 D 10 10 9 8