claudius
claudius

Reputation: 1005

How to change y-axis scale in a R boxplot function?

When I do a boxplot diagram with the R boxplotfunction, this function prints the y-axis automatically.

library(datasets)

boxplot(cars[c('speed', 'dist')],
        col = "lightgray")

In the ?boxplot I found the ylim parameter that change the y-axis limits, but not change the scale. So I tried to use the axis function to divide the scale from 0 to 120 every 10: axis(4, at = seq(0, 120, 10)). But I'm not getting a satisfactory result.

I can't see where I'm making mistakes. Could someone help with this question?
Thanks in advance.

boxplot

Upvotes: 2

Views: 22488

Answers (3)

Vitali Avagyan
Vitali Avagyan

Reputation: 1203

library(datasets)
boxplot(cars[c('speed', 'dist')], col = "lightgray", ylim = range(0:120), yaxs = "i")
axis(4, at=seq(0, 120, 10))

enter image description here

The y-axis is on the right-hand side as you wanted I believe.

Upvotes: 4

Rui Barradas
Rui Barradas

Reputation: 76432

I am answering because the OP said in a comment that my comment did the job. I will also explain the code here.

There are two tricks to consider:

  1. First plot without the yaxis by setting argument yaxt = "n".
  2. Then plot the axis number 2, with the labels always perpendicular to the axis. This is done with las = 2.

So the final code is the following.

library(datasets)

boxplot(cars[c('speed', 'dist')],
        col = "lightgray", yaxt = "n")
axis(2, at = seq(0, 120, 10), las = 2)

enter image description here

Upvotes: 1

Achal Neupane
Achal Neupane

Reputation: 5719

You could use ggpubr instead. It let's you treat it as a gg object.

librabry(ggpubr)
library(reshape2)
df <- melt(cars)
p <- ggpubr::ggboxplot(data = df, x = "variable", y = "value", width = 0.8) +
  ggtitle("Plot of car") +
  xlab("my-xalabel") + ylab("my-ylabel")
>p

enter image description here

If you want in log scale:

p + ggpubr::yscale("log2", .format = TRUE)

enter image description here

Upvotes: 1

Related Questions