[R] plotting a double y axis when x and y lengths differ

Rolf Turner rolf.turner at xtra.co.nz
Wed Nov 16 08:34:24 CET 2011


Any time you use ``par(new=TRUE)'', you're probably doing something
wrong.  Avoid it like the plague.

Following up on Michael Weylandt's post:  plotCI() indeed has an xlim
argument (i.e. the "..." arguments which get passed to plot.default()
can include xlim).

Note that plotCI() also has an ***add*** argument!  Use this,  rather than
mucking about with par(new=TRUE)!

     cheers,

             Rolf Turner

On 16/11/11 17:51, Vinny Moriarty wrote:
> Hello All,
>
> Many thanks to the help I have received so far.
>
>
> Here is an example data set I hope to plot
>
> Data1
>    Year Data   SE
> 1 2005    2 0.01
> 2 2006    4 0.01
> 3 2007    5 0.01
> 4 2008    2 0.01
> 5 2009    3 0.01
> 6 2010    6 0.01
>
>
> Data2
>    Year Data SE
> 1 2006   32  1
> 2 2007  100  2
> 3 2008   60  4
> 4 2009   67  3
> 5 2010    8  1
>
>
> Notice Data2 has one less years worth of data than Data1 (which is my
> problem)
>
> I am fond of using plotCI as it makes creating error bars and offsetting
> overlapping error bars so easy, and double y-axis plots are a breeze
>
> library(plotrix)
> library(gplots)
> offset=.08
>
> plotCI(x=Data1$Year, y=Data1$Data, uiw=Data1$SE,lty=1,sfrac=.005, type="l",
> gap=0, col="red", xlab="YEAR")
>
> par(new=TRUE)
>
> plotCI(x=(Data2$Year) +offset, y=Data2$Data, uiw=Data2$SE,lty=1,sfrac=.005,
> type="l", gap=0, col="blue", xaxt="n",yaxt="n",xlab="",ylab="")
>
> axis(4)
>
>
>
>
> This above code is sooo close to what I want. It creates a plot where even
> though one data set contains much larger numbers than the other, both fit
> on the same plot without me having to manually adjust the Y axis. And the
> generating the second Y-axis is simple. But my problem is with the x axis
>
> The issue is that because the two Data sets are not the same size, the
> Data2 line gets stretched along the x-axis in the plot to cover the missing
> first year. So it looks like Data2 has data in 2005.
>
> I can't plot the Data2 line by the year in Data1 aka (
> plotCI((x=(Data1$Year) +offset, y=Data2$Data.......) because the data are
> not of equal size
>
> I was thinking something along the line of pulling out the matching years
> such as (   plotCI(x=(Data1[c(2:6),1])+offset, y=Data2$Data.......)  but I
> could not get it to work.
>
>
> Any suggestions will earn you well earned programing karma and many thanks
> from me.



More information about the R-help mailing list