[R] adding points in plot loop --> try using matplot() !

Martin Maechler maechler at stat.math.ethz.ch
Wed Mar 23 12:29:52 CET 2016


>>>>> Duncan Murdoch <murdoch.duncan at gmail.com>
>>>>>     on Wed, 23 Mar 2016 05:55:43 -0400 writes:

    > On 23/03/2016 5:36 AM, catalin roibu wrote:
    >> Dear R users,
    >> 
    >> I have a dataframe with 6 columns and I want to create a plot (with for
    >> loop). My question is how to add points in the for loop? I tried this code,
    >> but without success.
    >> 
    >> vv<-rbind(colnames(ext))
    >> for(i in 1:ncol(vv)){
    >> with(ext, plot(rownames(ext), ext[,i], type="p",las=1,
    >> bty="n",cex.main=2, cex.axis=1.5))
    >> }
    >> 
    >> Please help me to solve that!

    > You can call the points() function to add points to an existing plot. 
    > The main difficulty is that the initial call to plot() establishes the 
    > axes and coordinate system; if later points fall outside the plot area, 
    > they won't be shown.  So you may need to work out xlim and ylim in advance.

Indeed!  ... and that's why R has inherited the  matplot() / matlines()
utility functions from S for about 20 years now. These do plot
all the columns of a numeric matrix and solve the xlim/ylim problem for you.

As the above R code is not reproducible (we do not have your 'ext'), 
I have not tried if your use of "rownames"/"colnames" is easily
portable to matplot.  If not (which I doubt), just take
matplot() as a template to writer your own function.
BTW: Your usage of  with(.) seems entirely unnecessary ..

Martin Maechler



More information about the R-help mailing list