Stefano Lombardi
Stefano Lombardi

Reputation: 1589

Axis labels overlapping with axis values

I have a problem in correctly plotting the labels of the following graph:

scatterhist = function(x, y, xlab="", ylab=""){
  zones=matrix(c(2,0,1,3), ncol=2, byrow=TRUE)
  layout(zones, widths=c(4/5,1/5), heights=c(1/5,4/5))
  xhist = hist(x, plot=F, breaks=10)
  yhist = hist(y, plot=F, breaks=10)
  top = max(c(xhist$counts, yhist$counts))

  par(mar=c(3,3,1,1))
  plot(x, y)

  par(mar=c(0,3,1,1))
  barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)

  par(mar=c(3,0,1,1))
  barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)

  par(oma=c(3,3,0,0))
  mtext(xlab, side=1, line=1, outer=TRUE, adj=0, 
    at=.8 * (mean(x)-min(x))/(max(x)-min(x)))
  mtext(ylab, side=2, line=1, outer=TRUE, adj=0, 
    at=.8 * (mean(y)-min(y))/(max(y)-min(y)))
}

When I type:

scatterhist(x[,6], x[,7], xlab="Cost of Taxi", ylab="Cost of Fuel")

the labels overlap with the axes values. However, if I type:

scatterhist(x[,6], x[,7], xlab="Cost of Taxi", ylab="Cost of Fuel")
scatterhist(x[,6], x[,7], xlab="Cost of Taxi", ylab="Cost of Fuel")

the second graph is correctly displayed... Can anyone help me with this issue? I have also tried to open the graph window through windows() before the first plot, but this doesn't work...

Thanks! Stefano

Upvotes: 3

Views: 3678

Answers (1)

plannapus
plannapus

Reputation: 18759

Your par(oma=c(3,3,0,0)) line should come before the first par(mar=...) call since it should be applied to the whole device region (i. e. you can't change the size of the outer margin if you already plotted some graphs).

scatterhist = function(x, y, xlab="", ylab=""){
    zones=matrix(c(2,0,1,3), ncol=2, byrow=TRUE)
    layout(zones, widths=c(4/5,1/5), heights=c(1/5,4/5))
    par(oma=c(3,3,0,0))

    xhist = hist(x, plot=F, breaks=10)
    yhist = hist(y, plot=F, breaks=10)
    top = max(c(xhist$counts, yhist$counts))

    par(mar=c(3,3,1,1))
    plot(x, y)

    par(mar=c(0,3,1,1))
    barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)

    par(mar=c(3,0,1,1))
    barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)

    mtext(xlab, side=1, line=1, outer=TRUE, adj=0, 
        at=.8 * (mean(x)-min(x))/(max(x)-min(x)))
    mtext(ylab, side=2, line=1, outer=TRUE, adj=0, 
        at=.8 * (mean(y)-min(y))/(max(y)-min(y)))
    }

Upvotes: 2

Related Questions