[R] two colors in one variable in legend

ani jaya g@@@uu| @end|ng |rom gm@||@com
Thu Jul 21 02:20:10 CEST 2022


Dear R-Help,

I need to plot two colors in legend in one variable. It is basically
same as this:

https://stackoverflow.com/questions/31004236/r-legend-boxes-with-more-than-one-colour

but I am not confident enough to change the legend script. What I want
to achieve is the color in legend is side by side or half by half, for
example, for oni blue and red and pink and lightblue for dmi.
Here is my script and data.

>dput(head(oni,30))
c(V11 = 0.55, V12 = 0.33, V13 = 0.09, V14 = 0.2, V15 = 0.13,
V16 = 0.37, V17 = 0.02, V18 = -0.23, V19 = -0.12, V110 = -0.11,
V111 = 0.1, V112 = 0.36, V21 = -0.45, V22 = -0.45, V23 = -0.02,
V24 = -0.17, V25 = -0.11, V26 = -0.15, V27 = -0.43, V28 = -0.18,
V29 = -0.07, V210 = -0.03, V211 = -0.27, V212 = 0.07, V31 = -0.04,
V32 = -0.13, V33 = -0.02, V34 = 0.24, V35 = 0.65, V36 = 0.92)


>dput(head(dmi,30))
c(V11 = -0.093, V12 = -0.12, V13 = -0.317, V14 = -0.02, V15 = 0.014,
V16 = -0.268, V17 = -0.564, V18 = -0.71, V19 = -0.639, V110 = -0.498,
V111 = -0.294, V112 = -0.413, V21 = -0.136, V22 = 0.056, V23 = 0.127,
V24 = 0.168, V25 = 0.062, V26 = -0.126, V27 = -0.463, V28 = -0.516,
V29 = -0.651, V210 = -0.447, V211 = -0.204, V212 = 0.05, V31 = 0.209,
V32 = 0.246, V33 = 0.154, V34 = 0.194, V35 = 0.302, V36 = 0.369

#scriptplot(oni[1:30],ylim=c(-3,3),type="l", pch=3, col="white",
     ylab=expression(bold("ONI3.4 & DMI (\u00B0C)")),
     xlab=expression(bold("Year")),lwd=2)
abline(h=0,lwd=2,col="black")
polygon(c(1,1:30,30),c(0,ifelse(oni[1:30]>0,oni,0),0),col="red")
polygon(c(1,1:30,30),c(0,ifelse(oni[1:30]<0,oni,0),0),col="blue")
segments(c(1,1:30,30),0,c(1,1:30,30),c(0,ifelse(dmi[1:30]>0,dmi,0),0),col="pink",
lwd=2)
segments(c(1,1:30,30),0,c(1,1:30,30),c(0,ifelse(dmi[1:30]<0,dmi,0),0),col="lightskyblue",lwd=2)
legend("bottomleft",legend=c("ONI3.4","DMI"), fill=c("red","lightpink"),
       density=c(NA,NA))

Any help is very welcome.
Thank you.

best,
Ani



More information about the R-help mailing list