user1946152
user1946152

Reputation: 375

Plotting a graph using vectors of different length in R

I have one array and a vector as follows-

v<-c(2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0)
result<-matrix(1,9,1000)

Now for every value in v i want to plot an entire row in result matrix. For ex. for value 2.4 in v i want to plot the points (2.4,result[1,1]),(2.4,result[1,2]),(2.4,result[1,3]) upto (2.4,result[1,1000]),

When i try to do that using

 points(v[1],result[1,],pch=".")

i get an error- x and y are not of equal length.

Is there any way i can do that?

Upvotes: 0

Views: 2507

Answers (2)

Andy Clifton
Andy Clifton

Reputation: 5056

From what you describe, you could consider your v array to be a label for your data. Let's plot the data with that in mind, and use ggplot2:

Start by turning your array v into something with the same size as result:

require('ggplot2')
require('reshape')

# OP's original data
v<-c(2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0)    
v.mat <- matrix(v,9,1000)

# OP's original data
result<-matrix(1,9,1000)

Next, we use melt to turn this data into a long data frame

v.mat.melt <- melt(v.mat)
result.melt <- melt(result)

Then combine the bits we need into a data frame:

# combine data
data <- data.frame('v' = v.mat.melt[,3],
                   'obs' = result.melt[,2],
                   'result' = result.melt[,3])

Note that I added 'obs' for 'observation', which is the index of the observation. I don't use it, but it could be handy.

Finally, plot it all up

d <- ggplot(data = data,
            aes(x = v,
                y = result,
                color = v)) + 
  geom_point()
print(d)

et voila: results

Upvotes: 1

Se&#241;or O
Se&#241;or O

Reputation: 17412

plot(cbind(v[1], result[1,])) will recycle v[1] as necessary.

Upvotes: 4

Related Questions