如何更改 R boxplot 函数中的 y 轴刻度

How to change y-axis scale in R boxplot function

当我使用 R boxplot函数绘制箱线图时,此函数会自动打印 y 轴。

library(datasets)

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

?boxplot 中,我发现 ylim 参数可以更改 y 轴限制,但不会更改比例。所以我尝试使用 axis 函数将比例从 0 到 120 每 10 分一次: axis(4, at = seq(0, 120, 10))。但是我没有得到满意的结果。

我看不出我哪里出错了。有人可以帮忙解答这个问题吗?
提前致谢。

您可以改用 ggpubr。它让您将其视为 gg 对象。

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

如果你想要对数刻度:

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

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

我相信 y 轴在您想要的右侧。

我回答是因为 OP 在评论中说我的评论起到了作用。我也会在这里解释代码。

有两个技巧需要考虑:

  1. 第一个没有 y 轴的绘图通过设置参数 yaxt = "n".
  2. 然后绘制轴号 2,标签始终垂直于轴。这是通过 las = 2.
  3. 完成的

所以最终的代码如下

library(datasets)

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