简体   繁体   English

如何在R箱图功能中更改y轴比例

[英]How to change y-axis scale in R boxplot function

When I do a boxplot diagram with the R boxplot function, this function prints the y-axis automatically. 当我使用R boxplot功能制作箱线图时,此功能会自动打印y轴。

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. ?boxplot ylim ,我发现ylim参数可以更改y轴限制,但不能更改比例。 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)) . 因此,我尝试使用axis函数将比例从0到120每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. 提前致谢。

箱形图

You could use ggpubr instead. 您可以改用ggpubr It let's you treat it as a gg object. 让我们将其视为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

在此处输入图片说明

If you want in log scale: 如果要以对数刻度:

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))

在此处输入图片说明

The y-axis is on the right-hand side as you wanted I believe. 我相信,y轴位于右侧。

I am answering because the OP said in a comment that my comment did the job. 我之所以回答,是因为OP在评论中说我的评论起到了作用。 I will also explain the code here. 我还将在这里解释代码。

There are two tricks to consider: 有两个技巧要考虑:

  1. First plot without the y axis by setting argument yaxt = "n" . 通过设置参数yaxt = "n"绘制没有y轴的第一个图。
  2. Then plot the axis number 2, with the labels always perpendicular to the axis. 然后绘制轴编号2,使标签始终垂直于轴。 This is done with las = 2 . 这是通过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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM