0

I have data in R that is in the form of : week -year (e.g. 21-03, the 21st week of 2003). In my real data, these dates appear in character format.

I am trying to plot this data in R, but the date formatting is not working properly. I tried to recreate the data as close as I can, and then run the plots:

library(dplyr) 
 library(ggplot2) 
 library(reshape2)  
library(scales)
library(lubridate)       

  Table_1 <- data.frame(  "Col_A" = c("21-03", "21-03", "21-03", "21-04", "21-04", "21-04", "21-05", "21-05", "21-05"), 
 "Col_B" = c("AAA", "AAB", "AAC", "AAA", "ABB", "AAC", "AAA", "AAB", "AAC"), 
 "Col_C" = c(111, 122.5, 9, 727, 66.4, 3, 992, 88, 12)      )

Table_1$col_A_Date <- as.Date(Table_1$col_A, format = "%W-%y")
 Table_1$Col_B = as.factor(Table_1$Col_B) 
 Table_1$Col_C = as.numeric(Table_1$Col_C) 

melt = melt(Table_1, id = c("Col_A"))  

p = ggplot(melt, aes(x = Col_A, y=value, group = 1)) + geom_line(aes(color=variable)) +
 facet_grid(variable ~., scales = "free_y") + scale_x_date(date_labels = "W%-%y", date_breaks = '1 month') + theme(axis.text, x = element_text(angle = 45))   

final = p + scale_y_continuous(labels = comma)  

Can someone please tell me what I am doing wrong?

Thanks

stats_noob
  • 3,127
  • 2
  • 8
  • 27
  • I think you are using the wrong formatting for your dates. Can you have a look at this post: https://stackoverflow.com/questions/32470414/convert-week-number-to-date `Table_1$Col_A – Col Bates - collynomial Dec 22 '20 at 08:17

1 Answers1

2

There are some typos in your post and the column which has date in it is col_A_Date so you need to use that as an id variable in melt and drop Col_A. Here is a tidyverse approach.

library(tidyverse)

Table_1 %>%
  mutate(col_A_Date = as.Date(Col_A, format = "%W-%y")) %>%
  select(-Col_A) %>%
  mutate(across(c(Col_B, Col_C), as.character)) %>%
  pivot_longer(cols = -col_A_Date) %>%
  ggplot(aes(x = col_A_Date, y=value, group = 1)) + 
  geom_line(aes(color=name)) +
  facet_grid(name ~., scales = "free_y") + 
  scale_x_date(date_labels = "W%-%y", date_breaks = '1 month') + 
  theme(axis.text = element_text(angle = 45))   
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
  • thank you for your reply. is it possible to change to change the date format just with one line? something like this: Table_1$Col_A – stats_noob Dec 22 '20 at 08:21
  • i dont have tidyverse on my work work computer (my work computer has no internet access and no usb port .... it only comes with a few pre installed libraries in R such as dplyr, ggplot2, lubridate, reshape2). – stats_noob Dec 22 '20 at 08:22
  • You can use `Table_1$col_A_Date – Ronak Shah Dec 22 '20 at 08:25