Patthebug Patthebug - 2 months ago 18
R Question

Plotting multiple time series on the same plot using ggplot()

I am fairly new to R and am attempting to plot two time series lines simultaneously (using different colors, of course) making use of ggplot2.

I have 2 data frames. the first one has 'Percent change for X' and 'Date' columns. The second one has 'Percent change for Y' and 'Date' columns as well, i.e., both have a 'Date' column with the same values whereas the 'Percent Change' columns have different values.

I would like to plot the 'Percent Change' columns against 'Date' (common to both) using ggplot2 on a single plot.

The examples that I found online made use of the same data frame with different variables to achieve this, I have not been able to find anything that makes use of 2 data frames to get to the plot. I do not want to bind the two data frames together, I want to keep them separate. Here is the code that I am using:

ggplot(jobsAFAM, aes(x=jobsAFAM$data_date, y=jobsAFAM$Percent.Change)) + geom_line() +
xlab("") + ylab("")


But this code produces only one line and I would like to add another line on top of it.
Any help would be much appreciated.
TIA.

Answer

ggplot allows you to have multiple layers, and that is what you should take advantage of here.

In the plot created below, you can see that there are two geom_line statements hitting each of your datasets and plotting them together on one plot. You can extend that logic if you wish to add any other dataset, plot, or even features of the chart such as the axis labels.

library(ggplot2)

jobsAFAM1 <- data.frame(
  data_date = runif(5,1,100),
  Percent.Change = runif(5,1,100)
  )

jobsAFAM2 <- data.frame(
  data_date = runif(5,1,100),
  Percent.Change = runif(5,1,100)
)


p <- ggplot() + 
  geom_line(data = jobsAFAM1, aes(x = data_date, y = Percent.Change, color = "red")) +
  geom_line(data = jobsAFAM2, aes(x = data_date, y = Percent.Change, color = "blue"))  +
  xlab('data_date') +
  ylab('percent.change')