Günal
Günal

Reputation: 751

Combining two plot in R

I wish to compare the observed values to the fitted ones. To do so, I decided to use a plot in R. What I want to do is to plot X vs Y and X vs Y.fitted on the same plot. I have written some code, but it is incomplete. My plot needs to look like this one below. On the plot, circles and crosses represent the observed and fitted values respectively

enter image description here

set.seed(1)
x <- runif(8,0,1)
y <- runif(8,0,1)
y.fitted <- runif(8,0,1)
plot(x,y,pch=1)
plot(x,y.fitted,pch=5)

Upvotes: 0

Views: 122

Answers (3)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

A solution with ggplot2 giving a better and neat graph outlook:

library(ggplot2)

df = data.frame(x=runif(8,0,1),y=runif(8,0,1),y.fitted=runif(8,0,1))
df = melt(df, id=c('x'))

ggplot() + geom_point(aes(x=x,y=value, shape=variable, colour=variable), df) 

Upvotes: 1

Martijn vd Voort
Martijn vd Voort

Reputation: 366

running plot the second time will create a new one. You could use points

set.seed(1)
x <- runif(8,0,1)
y <- runif(8,0,1)
y.fitted <- runif(8,0,1)
plot(x,y,pch=1)
points(x,y.fitted,pch=5)

Upvotes: 1

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

In your code, the second plot will not add points to the existing plot but create a new one. You can + use the function points to add points to the existing plot.

plot(x, y, pch = 1)
points(x, y.fitted, pch = 4)

Upvotes: 4

Related Questions