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.
Method 1: Using Basic R methods First, we create a data vector that has data for all the time series that have to be drawn. Then we plot the time series using the first dataset and plot() function. Then add other time series using line() function to the existing plot.
This section shows how to use the ggplot2 package to draw a plot based on two different data sets. For this, we have to set the data argument within the ggplot function to NULL. Then, we are specifying two geoms (i.e. geom_point and geom_line) and define the data set we want to use within each of those geoms.
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) ) 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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With