2

I am trying to make a box plot with the following code

boxplot(depy ~ depx, outline = FALSE, ylim = c(-20,20))

which works fine

enter image description here

When I try to add a limit for the x-axis

boxplot(depy~depx,outline=FALSE,xlim=c(-10,10),ylim=c(-20,20))

I get this

enter image description here

which looks like it has a wrong scale and doesn't show the tick marks and axis labels outside the area with the plotted values.

Any help to fix this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
user3910073
  • 511
  • 1
  • 6
  • 23
  • Check `?boxplot`. The x-axis variable is the grouping variable and it is usually a factor as mentioned in the documentation. Why would you need to set limits to the x-axis anyway? Above you do not see the scales and the tick marks because there are no categories with those numbers on the x-axis. I suggest you keep the first plot but if you really want to go with the second just add zeros for the values -20 to -5 and 7 to 20 on the x-axis. – LyzandeR Oct 23 '15 at 09:44
  • @LyzandeR thanks for the explanation. I want to set the limits to compare different plots. I could add zeros as suggested but to me also the scale looks wrong (xlim=c(-10,10)) – user3910073 Oct 23 '15 at 09:48
  • Add zeros, don't use the limit and it will be fixed on its own since the x axis is using categories (but I really think this is the wrong way) – LyzandeR Oct 23 '15 at 10:16
  • 1
    The scale looks exactly like what I would expect. The x-axis in your plot is showing factor levels, which are internally coded as integers, with 1 = "-6", 2 = "-3", 3 = "0", etc. So when you change your x-limits to `c(-10, 10)`, you get -10 to 0 blank, 1-5 with your factor levels, and then 6-10 blank again. – Benjamin Oct 23 '15 at 11:27

1 Answers1

1

As mentioned in the comments x-axis for boxplot is a grouping variable, and usually a factor.

We could extend it using xlim (I'd consider this a wrong way, but not impossible). In below example data, there are 3 groups (4=1, 6=2, 8=3), and if we want to extend it by 1 on both sides, we need to add 0th and 4th on x-axis:

#example data
d <- mtcars

#using xlim
boxplot(mpg ~ cyl, d, xlim = c(0, 4))

enter image description here

The better way is to fix the factor levels before plotting:

#better way using factor levels
d$cyl <- factor(d$cyl, levels = as.character(c(2, sort(unique(d$cyl)), 10)))
boxplot(mpg ~ cyl, d)

enter image description here

zx8754
  • 52,746
  • 12
  • 114
  • 209