Minnow
Minnow

Reputation: 1811

How to add axis labels to a simple.scatterplot (UsingR)

The package UsingR has some great out of the box plotting tools. However, using the simple.scatterplot function I can't figure out how to add axis labels.

library(UsingR)

simple.scatterplot(iris$Sepal.Length, iris$Sepal.Width, xlab='hello axis')

Error in plot.default(x, y, xlim = xrange, ylim = yrange, xlab = "x",  : 
  formal argument "xlab" matched by multiple actual arguments

The graph can of course be produced without using the xlab arg, and I tried using the mtext command, but the label ends up in the middle of the page.

mtext(side=1, text='hello axis')

enter image description here

I tried editing the function itself without success either:

mysimple.scatterplot <- function (x, y) 
{
  def.par <- par(no.readonly = TRUE)
  n <- length(x)
  xhist <- hist(x, sqrt(n), plot = FALSE)
  yhist <- hist(y, sqrt(n), plot = FALSE)
  top <- max(c(xhist$counts, yhist$counts))
  xrange <- c(min(x), max(x))
  yrange <- c(min(y), max(y))
  nf <- layout(matrix(c(2, 0, 1, 3), 2, 2, TRUE), c(3, 1), 
               c(1, 3), TRUE)
  layout.show(nf)
  par(mar = c(3, 3, 1, 1))
  plot(x, y, xlim = xrange, ylim = yrange, xlab = 'Hello X-axis', ylab = 'Hello Y-axis', 
       ...)
  abline(lm(y ~ x))
  par(mar = c(0, 3, 1, 1))
  barplot(xhist$counts, axes = FALSE, ylim = c(0, top), space = 0, 
          col = gray(0.95))
  par(mar = c(3, 0, 1, 1))
  barplot(yhist$counts, axes = FALSE, xlim = c(0, top), space = 0, 
          col = gray(0.95), horiz = TRUE)
  par(def.par)
}

Upvotes: 1

Views: 200

Answers (1)

zw324
zw324

Reputation: 27190

The cause is here:

layout.show(nf)
par(mar = c(3, 3, 1, 1)) # <-- Here
plot(x, y, xlim = xrange, ylim = yrange, xlab = 'Hello X-axis', ylab = 'Hello Y-axis', 
     ...)

The margins are changed to a small value thus the labels are not in the plot, they are outside of the area.

Upvotes: 2

Related Questions