 1000111000 - 3 years ago 120
R Question

# I can't add axis() to plot when using abline(lm()), why?

I am struggling because I am just trying to add my own x-axis values and tickmarks to a plot which shows also the linear regression.

It seems that OR I add the abline OR I add the axis. I can't do both!

Why?

Example data:

``````df = data.frame(year = c(1901:2000), total = ceiling(runif(100, 2, 3000)))
``````

This code works ONLY for abline():

``````plot(df\$year, df\$total, xaxt='n')
abline(lm(df\$total ~ df\$year))
axis(1, at = seq(1,100, by = 10), labels = seq(1901, 2000, by = 10)) #this line does not work
``````

This code works only for axis():

``````plot(df\$total, xaxt='n')
abline(lm(df\$total ~ df\$year)) #this line does not work
axis(1, at = seq(1,100, by = 10), labels = seq(1901, 2000, by = 10))
``````

thank you Axeman
In your first example, the x-axis actually goes from 1901 to 2000. You therefore need to define `at` in that range, otherwise your values fall outside the plot and are invisible. Simply do:
``````plot(df\$year, df\$total, xaxt='n')
The second example your `axis` call works because you are plotting `index` on the x-axis, which just counts from 1 to n observations (in this case 100). The `abline` is not visible, since it is not within the range of that plot.