10

I want to plot, in the same graph, two different sets of points: A = [1 2; 3 4] and B = [1 3; 2 4]. I need to store the plot, so my idea is to use myPlot <- qplot followed by ggsave.

With such an approach, how can I plot multiple datasets without getting the error formal argument "data" matched by multiple actual arguments?

Here is the code I am using now:

yPlot <- qplot(A[,1], A[,2], data = A[1:2], geom="point",
                B[,1], B[,2], data = B[1:2], geom="point") + xlim(0, 10) 
ggsave(filename="Plot.jpg", plot=myPlot, width = 12, height = 8)

1 Answer 1

23

Here's a template for plotting two data frame in the same figure:

A = data.frame(x = rnorm(10),y=rnorm(10))
B = data.frame(x = rnorm(10),y=rnorm(10))
ggplot(A,aes(x,y)) +geom_point() +geom_point(data=B,colour='red') + xlim(0, 10) 

or equivalently:

qplot(x,y,data=A)  +geom_point(data=B,colour='red') + xlim(0, 10) 

If you want to plot to figures side by side, see ?par and look for the descriptions of 'mfcol' and 'mfrow'

In addition to ggsave, see ?pdf.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for that! What if the A and B have different size?
Do you mean different number of rows in the data frames? If so, both solutions should still work.
Are you using matrices or data frames? If so you probably want to coerce them to data frames using as.data.frame. Also, ggplot maps the asthetics to the variable names (ggplot treats position as an asthetic) which is why i didn't have to supply the names x and y to geom_point(). Hence you'll want to have data.frames with the same names. If your using the usual notation (2 rows X 10 columns) then you want to use something like: a = as.data.frame(t(A)); names(a) <- c('x','y')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.