I'm studying R and made a simple data to draw a scatter plot. Here is the simple code that I made:
library(lubridate)
df <- data.frame(date = c(20120324,20120329,20121216,20130216,20130725,20130729,20130930,20131015,20131124,20131225),
math=c(54,32,45,78,89,12,33,46,79,100),
physics=c(100,100,23,24,55,66,34,37,89,39))
df$date<-ymd(df$date)
math<-df$math
physics<-df$physics
date<-df$date
plot(date,math,xlab="year",ylab="math")
par(new=TRUE)
plot(date,physics,xlab="year",ylab="physics")
What I was trying to do was to draw the scatter plots simultaneously in one plane and give them labels to differentiate each other. So my goal is to plot math
and physics
using different colors. I think red and blue will be fine. I want to make x axis to represent the year. In date
column, 20120324
means March 24th, 2012.
CodePudding user response:
You can use functions in tidyverse
package to pivot your data into the longer format, and then plot using ggplot.
library(tidyverse)
df %>%
pivot_longer(-date) %>%
ggplot(aes(date, value, colour=name))
geom_point()
scale_x_date(breaks="year",
date_labels="%Y",
limits=as.Date(c("2012-01-01","2014-01-01")))