简体   繁体   中英

facet ggplot for grouped data and two variables with date in R

I want to plot a facet chart in R for my groups of Model No. so that each graph shows the 12 months data and two different colour lines for each Val1 and Val2.

Model No.   Date    Val1    Val2
a   01/10/2020  2.39    4.67
a   01/11/2020  5.15    6.05
a   01/12/2020  3.19    1.62
a   01/01/2021  8.76    11.65
a   01/02/2021  15.72   11.41
a   01/03/2021  10.92   11.91
a   01/04/2021  11.96   19.27
a   01/05/2021  11.52   15.58
a   01/06/2021  2.92    4.42
a   01/07/2021  4.89    6.01
a   01/08/2021  10.05   15.19
a   01/09/2021  3.46    4.85
b   01/10/2020  3.76    3.41
b   01/11/2020  0.88    1.25
b   01/12/2020  0.93    0.78
b   01/01/2021  1.87    1.88
b   01/02/2021  1.40    1.28
b   01/03/2021  1.58    1.29
b   01/04/2021  4.50    2.93
b   01/05/2021  5.31    5.45
b   01/06/2021  9.19    6.69
b   01/07/2021  4.09    3.11
b   01/08/2021  5.20    3.86
b   01/09/2021  4.39    3.76

I've added desired output from excel, somewhat along these lines. either a line chart or a bar graph next to each other showing both values(Val1 and Val2) comparison in each group.

Will be thankful if someone can help please. Thanks in advance.

测试数据

Try this approach. Reshape data to long keeping the model and then date. Then sketch the plot using facet_wrap() . Here the code:

library(ggplot2)
library(dplyr)
library(tidyr)
#Code
df %>% pivot_longer(-c(1,2)) %>%
  ggplot(aes(x=Date,y=value,color=name,group=name))+
  geom_line()+
  scale_x_date(breaks = '1 month')+
  facet_wrap(.~`Model No.`,scales = 'free',ncol = 1)+
  theme_bw()+
  theme(legend.position = 'bottom',
        axis.text.x = element_text(angle=90))+
  labs(color='Serie')

Output:

在此处输入图片说明

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