2

I've found an issue when setting pos = n when I use the axes command for creating charts in R. When the y-axis range is -6 to -1, it all works perfectly, but when my range is for example -5 to -2 the axes won't meet at the specified position; the y-axis omits the -5 label and tick mark.

The code for one of my charts is as follows:

x <- c(3179047.6, 1956470.4, 609295.9, 136037.6)
y <- c(-4.758698, -4.227640, -4.019197, -2.653719)

model_fit <- lm(y~x)
par(mar=c(2.1, 2.1, 2.5, 1.1)) # I want to reduce the white space around the margins

plot(x, y, axes = FALSE, xlab = NULL, ylab = NULL, # I set the axes manually afterwards
     ylim = c(c(min(0, y)), ceiling(max(y))),
     xlim = c(0, 1000000*ceiling(max(x)/1000000)))

lines(x4, predict(model_fit), lty = 2, col = "red")


mtext(side = 1, line = 1.1, expression(paste(epsilon^"2")), cex = 0.7) # Greek symbol squared, title repositioned, font size lowered.
mtext(side = 2, line = 0, "Y-axis Title\n(units)", cex = 0.7) # font size lowered
mtext(side = 3, line = -0.5, "Main\nTitle",
      cex = 0.8, font = 2)

axis(1, seq(0, 1000000*ceiling(max(x)/1000000), 1000000),
     labels = seq(0, 1000000*ceiling(max(x)/1000000), 1000000),tck = -0.02, cex.axis = 0.6, padj = -3, pos = floor(min(y4)))

axis(2, seq(floor(min(y)), ceiling(max(y)), 1),
     labels = seq(floor(min(y)), ceiling(max(y)), 1), tck = -0.02, cex.axis = 0.6, padj = 2, pos = 0)

par(mar=c(5.1, 4.1, 4.1, 2.1)) # Resetting the default margin sizes

For the axis() commands I've first set the range by seq(0, 1000000*ceiling(max(x)/1000000), 1000000), and then I repeated the command by setting labels = seq(0, 1000000*ceiling(max(x)/1000000), 1000000) to manually force the code to return the tick marks and labels at the correct position.

Then for the x-axis (axis 1), I set the position where it meets the y-axis (axis 2) at the minimum value of the y axis range by setting pos = floor(min(y4). The issue is for the chart produced by the above code, instead of having the y-axis extend down to meet the x-axis, there's a space and no tick or label for the -5 point.

This only happens when the range is between -2 and -5, for my chart where the range is -1 to -6, the two axes meet.

Is there some underlying code in the axis command I need to override?

James.H
  • 25
  • 6
  • Seems your `plot(ylim)` interferes with `axis`, maybe try to adjust it a little `ylim=c(c(min(0, y)*1.05), ceiling(max(y)))` – jay.sf Sep 26 '20 at 09:33
  • @jay.sf thanks, that's a great little quick-fix! :) Wonder if there is a way to prevent the ylim override completely. – James.H Sep 26 '20 at 10:13

0 Answers0