1

I have a problem. I am trying to plot a graph y = (6x - 20)/5*. However, the graph plots the axes on the far left and bottom. So, I use the abline() function to plot the axes, so the graph passes through the axes. However, I'd like the tick marks and numbers to be on the axes which the graph passes through, not on the left and bottom. Here's the code:

# Define the function
f <- function(x) (6*x - 20)/5

xmin <- -3.5; max <- 7

# Plot the graph
par(bg='transparent')

plot(f, from=xmin, to=xmax, col="#218e8d", lwd=7, xlab="", ylab="",
     xlim=c(xmin,xmax), ylim=c(-5,7), bty= "n", axes="FALSE", n=20000, 
     panel.first=c(abline(h=0, lwd=2, col="#636363"), 
                     abline(v=0, lwd=2, col="#636363"),
                     axis(1, at=seq(-3, 7, by=1), col="#636363"),
                     axis(2, at=seq(-5, 7, by=1), col="#636363")))

mtext("x", side=1, line=3); mtext("y", side=2, line=3)

Here's what the code above plots:

The axes that the graph does pass through are the ablines. The axes with the ticks and numbers, however, are on the left and bottom.

Here's an example of a plot that has the ticks and numbers in the right places:

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Tom
  • 440
  • 3
  • 10
  • I think this is a duplicate of https://stackoverflow.com/questions/30658177/r-plot-with-axes-in-the-center ? (or https://stackoverflow.com/questions/17753101/center-x-and-y-axis-with-ggplot2?rq=3 if you want to use ggplot ...) – Ben Bolker Jul 22 '23 at 15:51
  • @BenBolker I thought they would like to see the axes intersect at the _origin_. – jay.sf Jul 22 '23 at 20:21

1 Answers1

0

The trick is to use pos=0.

f <- function(x) (6*x - 20)/5

xmin <- -3.75; xmax <- 7

curve(f, from=xmin, to=xmax, axes=FALSE, col=4, asp=1)
axis(1, pos=0); axis(2, pos=0) 
grid()
box()

If you want to know where the curve intersects the x-axis, i.e. where f(x) == 0 so y shows the slope, you may want to minimize the abs of function f(x) using optimize.

(minimum <- optimize(function(...) abs(f(...)), c(0, 100))$minimum)
# [1] 3.333314

axis(1, minimum, pos=0, labels=round(minimum, 2), col=2, col.axis=2, cex.axis=.8)

enter image description here

Curve shows slope -20/5 on y-axis and intersects x-axis at 3.33.

jay.sf
  • 60,139
  • 8
  • 53
  • 110