Yang Yang
Yang Yang

Reputation: 900

Boxplot tick values for the y-axis in R?

I am trying to create a boxplot in R, however, I find that the figure has wrong tick values for the y-axis.

The .rdata is available at https://www.dropbox.com/s/vbgf3mhgd2mjx8o/Mydata2.rdata?dl=0

load("Mydata2.rdata",.GlobalEnv)
boxplot(Value~Type+Level, data=Mydata2)

As the figure shows, the y-axis is marked "0, 50, 100", however, my data range from -36.9 to 133.7. I wonder how to fix this? enter image description here

Upvotes: 1

Views: 5553

Answers (2)

Matthew Anderson
Matthew Anderson

Reputation: 348

Two methods:

  1. Set each tickmark individually via axis's at argument (at is a numeric vector defining each tickmark):
boxplot(Value~Type+Level, yaxt="n", data=Mydata2)
tickmarks = c(min(Mydata2$Value), max(Mydata2$Value))
axis(2, at = round(tickmarks,1))
  1. Define the range for your tickmarks via boxplot's ylim argument. So, to set the range for your tickmarks between -40 and 140:
boxplot(Value~Type+Level, data=Mydata2, ylim=c(-40,140))

Method #2 works sometimes but not always. Method #1 is more reliable and customizable and should therefore be used more often.

Upvotes: 3

M--
M--

Reputation: 28825

Here, I used min, mean, and max for the tick marks. You can set them to any value manually or even have more than 3 ticks. yaxt="n" prevents the default tick marks and then by using axis and setting the side to 2 (axis(2,...) I add my desired tick marks. Read about ?axis in R.

boxplot(Value~Type+Level, yaxt="n", data=Mydata2)
axis(2, 
     at=round(c(min(Mydata2$Value), mean(Mydata2$Value), max(Mydata2$Value)),1),
     labels = T)

Follow up question: How the default tick marks are computed?

"When at = NULL, pretty tick mark locations are computed internally (the same way axTicks(side) would)."

So, your code is working. Default tick marks are picked by boxplot so it is prettier (well pretty is subjective).

Upvotes: 5

Related Questions