简体   繁体   中英

R - how to do an XY plot with two datasets in same graph?

I have a quick R question (as I'm trying to learn how to use it). I'm trying to do a simple XY plot that will show data from 2 datasets (var1 and var2). I'm able to load all the data into variables with no problem, but I can only plot var1. When I try plotting Var2, I get "Error in xy.coords(x, y) : 'x' and 'y' lengths differ".

Any thoughts on how I can fix this?

Here is what I'm doing:

#dataset 1

val1_time <- data.frame(time=c("04/09/15 04:52:30", "04/09/15 06:04:30", "04/09/15 07:14:24"))
val1 <- c(5.05, 0.29, 1.1)
val1_time$time <- strptime(val1_time$time,"%m/%d/%y %H:%M:%S") 

#dataset 2

val2_time <- data.frame(time=c("04/09/15 12:00:00", "04/10/15 12:00:00", "04/11/15 12:00:00"))
val2  <- c(1.925294118, 0.4555, 0.42)
val2_time$time <- strptime(val2_time$time,"%m/%d/%y %H:%M:%S") 


plot(val1_time,val1,col="blue", pch=18)

lines(val2_time,val2,col=“red”, pch=18)

There are a number of mistakes in your code. First, when dealing with time series, it is essential to use a package such as zoo (ideal for dates without time) or xts (for dates and time). It allows you to merge time series easily, calculate returns, lag a series... Mistake that was fixed: You don't need $time in val1_time

library(xts);library(zoo)
#dataset 1
val1_time <- data.frame(time=c("04/09/15 04:52:30", "04/09/15 06:04:30", "04/09/15 07:14:24"))
val1_time<- strptime(val1_time$time,"%m/%d/%y %H:%M:%S")
val1 <- c(5.05, 0.29, 1.1)
val1_xts <-xts(val1,val1_time)

#dataset 2
val2_time <- data.frame(time=c("04/09/15 12:00:00", "04/10/15 12:00:00", "04/11/15 12:00:00"))
val2_time <- strptime(val2_time$time,"%m/%d/%y %H:%M:%S")
val2  <- c(1.925294118, 0.4555, 0.42)
val2_xts <-xts(val2,val2_time)

all_xts <-merge(val1_xts,val2_xts)
plot.zoo(all_xts,col=c("blue","red"), plot.type="single")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM