3
votes

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))

Any help, please? thank you

1
Hi, thank you. my real dataframe has got just two numeric variables: 'year' from 1901 to 2000 and 'total' that can be even random integer numbers. - 1000111000
thank you Axeman. this has been done. - 1000111000

1 Answers

3
votes

The x-axis does not necessarily go from 1 to 100. The units are defined by the scale of your variable.

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')
abline(lm(df$total ~ df$year))
axis(1, at = seq(1901, 2000, by = 10))

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.