-2

My sample data :

structure(list(year = c(2018, 2018, 2018, 2018, 2019, 2019), 
    month = c(9, 10, 11, 12, 1, 2), pred1 = c(-6.63356483810535, 
    -6.50968293287978, -1.54767782423655, -1.47812226859267, 
    -1.36788275407234, -1.28168637109063), pred2 = c(-1.42361872090391, 
    -1.3982815502715, -1.1409241475472, -1.1331066959139, -1.12562914109629, 
    -1.11814749991547)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

I would like to have month on x-axis and year on y-axis and draw line graph for both pred1 and pred2 and compare graphically. I appreciate help in doing R

Lalitha
  • 147
  • 10
  • Hi Lalitha, you'll want to use `ggplot2` and use a long form data frame. See https://stackoverflow.com/questions/16889526/plotting-multiple-variables-in-ggplot – TheSciGuy Mar 14 '19 at 19:14
  • Thanks for replying,but the post you have sent is reshaping the data.Is there any other option to do so . – Lalitha Mar 14 '19 at 19:19
  • @Lalitha curious, why don't you want to reshape the data? reshaping it long format aka tidy format is best-practice – infominer Mar 14 '19 at 19:23
  • My case is different,I have same x and y axis also I standardized the data before plotting – Lalitha Mar 14 '19 at 19:25
  • super basic approach `plot(a$pred1,type="l",col="red"); lines(a$pred2, type="l",col="blue")` – boski Mar 14 '19 at 19:26
  • I think you may be a little confused on month on the x-axis and year on the y-axis... – Dave Gruenewald Mar 14 '19 at 19:31

1 Answers1

0

This is how I understand your question around wanting the year on the y axis -- I've put it into vertical facets, with a line graph in each facet with month on the x and value on the y. Please clarify your original question if this is not what you're trying to do.

ggplot(df1, aes(month)) +
  geom_line(aes(y = pred1), color = "blue") +
  geom_line(aes(y = pred2), color = "red") +
  facet_grid(year~.)

enter image description here

If you want a legend to distinguish the two series, it will be simplest to reshape the data into long format so that the series name is a variable that can be mapped to an aesthetic, like color.

library(dplyr)
df1 %>%
  tidyr::gather(series, value, pred1:pred2) %>%
  ggplot(aes(month, value, color = series)) +
  geom_line() +
  facet_grid(year~.)

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53