user2064019
user2064019

Reputation: 21

Plotting 2 curves in the same graph in R

Using R, I need to plot 2 curves in the same graph. So, I have to plot x1 vs. y1 and x2 vs. y2. Here "x1" are random but known numbers in the range of 0 to 12; "x2" are random but known numbers in the range of 0 to 9; and similarly some other known ranges for y1 and y2.

I used the following code:

d<-read.csv("ni1.csv")       # Reading in the data
x1<-d[,1]
y1<-d[,2]

d2<-read.csv("ni2.csv")
x2<-d2[,1]
y2<-d2[,2]

plot(x1,y1,pch="*", col='blue',xlim=c(0, 12), ylim=c(0,1300),main='Load Vs. Extension   Curves',xlab='Extension', ylab='Load')
par(new=TRUE)
plot(x2, y2, pch="*", col= 'red',xlim=c(0, 9), ylim=c(0,1400), axes= FALSE, xlab='', ylab='' )

Now the issue is although I am getting the right curve for x1 vs. y1, the curve for x2 vs. y2 is in improper range. That is to say, the x-range for x2 vs. y2 is coming out to be outside the values that I have for plotting.

Can anybody help solve this? Thank you very much for your support...

Regards.

Upvotes: 1

Views: 38393

Answers (3)

agstudy
agstudy

Reputation: 121568

Another approach is simply to use par(new=TRUE) to overlay two distinct plots on top of each other.

vv <- ts(c(3875, 4846, 5128, 5773, 7327,
                6688, 5582, 3473, 3186,
                 rep(NA, 51))
plot(drunkenness, lwd=3, col="grey", ann=FALSE, las=2)
par(new=TRUE)
plot(nhtemp, ann=FALSE, axes=FALSE,col='blue')

enter image description here

Upvotes: 6

Gx1sptDTDa
Gx1sptDTDa

Reputation: 1588

You can use the ggplot2 package, but that requires you to reorder your data into one dataframe, with an extra column specifying categories.

library(ggplot2)
d <- read.csv('ni1.csv',header=T)
d2 <- read.cv('ni2.csv',header=T)
#assuming header names are ´x´ and ´y´ 
df <- rbind(d,d2)
df$labels[(length(d[,1])+1):length(df[,1])] <- 'ni2'
df$labels[1:length(d[,1])] <- 'ni1'
qplot(x,y,data=df,geom='line') + facet_wrap(~labels)

Upvotes: 1

sebastian-c
sebastian-c

Reputation: 15395

Consider using points instead. Replace your plot(x2, y2, ...) with:

points(x2, y2, pch="*", col= 'red')

Upvotes: 3

Related Questions