[R] Plot multiple lines, same plot, different axes?

Ron Thornton Ron.thornton at fao.org
Fri Dec 19 17:05:31 CET 2008


The plotrix package does this ().  However, maybe only for lines.

The code below will plot as many graphs of different types one on another,
and it contains a plot with a different axis. The graphs are self scaling
for y axis and date axis.

I have included background code for setting up date data, + the table used
for graphing.

(It looks much more intelligible in Tinn-R.)

> names(survis)
 [1] "Province"      "District"      "SubDistrict"   "Village"       "Date"
"Activity"      "Status"        "RapidTestDone" "AnigenResult" 
[10] "HPAICompEvent"

class(survis$Date)
[1] "POSIXt"  "POSIXct"

#SET UP DATA
survis2<-survis
#rename fields
#Return date as month number
survismth<-as.numeric(format(survis2$Date, "%m"))
#set up axis labels
date.bins <- seq(from = min(survis2$Date), format = "%d/%m/%y", to =
max(survis2$Date), format = "%d/%m/%y", by = "1 month")
date.lab <- as.character(date.bins, format = "%b-%y")


print(join6)
   mthvis    0   1 testsdone anigenpos testpercr
4     954  819 135       135       105     11.01
5    2090 1929 161       161       114      5.45
6    2723 2545 178       178       126      4.63
7    2600 2460 140       140        93      3.58
8    2580 2392 188       188       106      4.11
9    2415 2240 175       175       104      4.31
10   2354 2263  91        91        42      1.78
11   1595 1526  69        69        36      2.26


#GRAPH THE RESULTS 
par(las=2)
mthlgth<-max(survismth)-min(survismth)+1 
plotvis<-barplot(join6[,"mthvis"],col="grey90",main="Visit numbers, test
numbers and HPAI detection rates\n - ALL PROVINCES",font.main=4,ylab="Number
of visits",border="grey20",ylim = c(0, max(join6[,"mthvis"]+20)), space=0,
xlim=c(0,mthlgth),names=date.lab)
#Second barplot overlying
par(new = TRUE)
plottests<-barplot(join6[,"anigenpos"],col="dark green",space=0, axes=FALSE,
names.arg="", ylim=c(0, max(join6[,"mthvis"]+20)))  #no axes, ylim to align
y axis
#Create graph with second plot with second axis with different scale, with
points centred on barplot columns
par(new = TRUE)  ; par(las=0)
plotperc<-plot(join6[,"testpercr"], type = "o", axes = FALSE, bty = "n",
xlab = "", ylab="", col="red",lwd=2,lty=1, xlim=c(0.5,(mthlgth+0.5)))
axis(side=4, at = pretty(range(testpercr)), col="red", lwd=2)
mtext("HPAI diagnoses per 100 visits", side = 4, line = -1.15, outer =
FALSE, at = NA, adj = NA, padj = NA, cex = NA, col = NA, font = NA)
savePlot(filename = "ALL PROVINCES", type = c("png"), device = dev.cur())


Ron Thornton
ron.thornton at fao.org



More information about the R-help mailing list