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

Jim Lemon jim at bitwrit.com.au
Wed Nov 16 10:52:05 CET 2011


On 11/16/2011 03:51 PM, 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.
>
Hi Vinny,
This is one way to do it:

offset<-0.05
plot(Data1$Year-offset,Data1$Data,type="b",ylim=c(0,110))
points(Data2$Year+offset,Data2$Data,type="b")
dispersion(Data1$Year-offset,Data1$Data,Data1$SE)
dispersion(Data2$Year+offset,Data2$Data,Data2$SE)

Not too elegant, but it gets the job done.

Jim



More information about the R-help mailing list