16

I'm having trouble setting my axis range in r. My data only has values from 2 to 9 on the x axis but I want it to go from 1 to 10. Any quick tips please?

head(SS)
  Phase Bed Site ACC X.M.SA
1     1   1    1  NG     NO
2     1   1    2  NG     NO
3     1   1    3  SG     NO
4     1   1    4  SG     NO
5     1   1    5  SG     NO
6     1   2    1  SG     NO

XMSA<-factor(SS$X.M.SA)
ACC<-factor(SS$ACC,ordered = TRUE,levels=c("NG","SG","LG","MG","HG"))

boxplot(ACC[XMSA=="MSSA"]~SS$Bed[XMSA=="MSSA"],
xlab="Bed",ylab="Growth",
las=1, yaxt="n",ylim=c(1,5),xlim=c(1,10))
axis(2, at=c(1,2,3,4,5),labels=c("NG","SG","LG","MG","HG"),las=1)

enter image description here

HCAI
  • 2,213
  • 8
  • 33
  • 65

1 Answers1

17

Without data, I tried to reproduce your plot error:

plot(x=as.factor(2:8),y=2:8,xlim = c(1,10))

Which gives the following plot:

enter image description here

Changing your plot to:

boxplot(x= as.numeric(as.character(SS$Bed[XMSA=="MSSA"])),
y= ACC[XMSA=="MSSA"]
xlab="Bed",ylab="Growth",
las=1, yaxt="n",ylim=c(1,5),xlim=c(1,10))
axis(2, at=c(1,2,3,4,5),labels=c("NG","SG","LG","MG","HG"),las=1)

Might solve your problem.

Edit

It seems that the formula changes to factors and orders it from 1 to the number of items, so I'll use your trick on the y axis to solve this.

boxplot(ACC[XMSA=="MSSA"]~SS$Bed[XMSA=="MSSA"],
xlab="Bed",ylab="Growth",
las=1, yaxt="n",ylim=c(1,5),xlim=c(0,9),xaxt="n")
axis(2, at=1:5,labels=c("NG","SG","LG","MG","HG"),las=1)
axis(1, at=0:9,labels=1:10,las=1)
Mihai
  • 2,807
  • 4
  • 28
  • 53
DeveauP
  • 1,217
  • 11
  • 21
  • Thank you for looking at this. Bed is categorical ordinal. ACC is a factor. XMSA is categorical numerical. Your code produces one boxplot for me not for each bed... – HCAI Apr 01 '16 at 12:14
  • I edited my comment, new version may be what you are looking for. – DeveauP Apr 01 '16 at 12:38
  • 1
    Perfect! Thank you! Could you clarify why this isn't so straight forward as it might be? – HCAI Apr 02 '16 at 13:49
  • 1
    I did not check this, but in my opinion, either Bed is stored as a factor or it is coerced to a factor when using the formula. So it will order from 1 to 8 in the same as is it would disply text for example. You wanted to add 1 tick before and 1 after, so I forced the xlim to be 0 to 9, and changed the labels to be 1 to 10 to display as you wanted. – DeveauP Apr 04 '16 at 06:45