[R] having more than one plot in one figure

David Winsemius dwinsemius at comcast.net
Tue Apr 20 22:11:52 CEST 2010


On Apr 20, 2010, at 10:34 AM, kayj wrote:

>
> Hi All,
>
> I have been trying to plot multiple line plots with different colors  
> on one
> figure. in my example below I was able to plot cat vs num1 as a dot  
> plot
> connected with lines but was not able to do that for cat vs num2 and  
> I do
> not know how to add the third plot cat vs num3. below is my code
>
>
> df <- data.frame(cat=1:10, num1=rnorm(10), num2=rnorm(10),  
> num3=rnorm(10))
> plot(df$num1, type="b", col="red", xlab="categories", ylab="random  
> numbers")
> points(df$num1, type="p", pch=21, col="red",bg="red")    #plot "num1"
> points(df$num2, type="p", pch=21, col="green")   #plot "num2"
> legend(x="topright", legend=c("num1", "num2"), pch=c(16,16),
> col=c("red","green"))    #add a legend
>

Add the x values since points does not have exactly the same default  
behavior when given just one vector for plotting:

df <- data.frame(cat=1:10, num1=rnorm(10), num2=rnorm(10),  
num3=rnorm(10))
plot(df$num1, type="b", col="red", xlab="categories", ylab="random  
numbers")
points(1:10, df$num2, type="b", pch=21, col="red",bg="red")    #plot  
"num1"
points(1:10, df$num3, type="b", pch=21, col="green")   #plot "num2"
legend(x="topright", legend=c("num1", "num2"), pch=c(16,16),
col=c("red","green"))    #add a legend

If you want to have all of the random point visible than use range(c(df 
$num1, df$num2, df$num3) as your argument to ylim.


>
> how to make the second plot of type="b" and how to add a  third plot  
> cat vs
> num3?

I don't understand why you did not look at the help page for points  
and realize that type="b" would work.

>
> I appreciate your help
>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list