在不影响箱线图所依据的数据的情况下限制ggplot中箱线图中y轴的范围

Limiting the range of the y axis in a boxplot in ggplot without affecting the data on which the boxplot is based

我正在使用 ggplot 创建箱线图。代码如下:

ggplot(my_data, aes(x = as.factor(viotiko), y = pd_1year, fill = as.factor(viotiko))) + geom_boxplot() +
  labs(title="Does the PD differ significantly by 'Viotiko' group?",x="Viotiko Group", y = "PD (pd_1year)") 

这将输出下图:

接下来,我想关注 y 值的范围 --[0, 0.05] -- 我再次 运行 更改了参数的代码。我并不是要排除数据并改变均值和分布,而只是要关注特定范围的 y 值。代码又是这样的:

ggplot(my_data, aes(x = as.factor(viotiko), y = pd_1year, fill = as.factor(viotiko))) + geom_boxplot() +
  labs(title="Does the PD differ significantly by 'Viotiko' group?",x="Viotiko Group", y = "PD (pd_1year)") +
  scale_y_continuous(breaks =seq(0, .05, .01), limit = c(0, 0.05))

这返回了警告 "Removed 173664 rows containing non-finite values (stat_boxplot)." 并输出了下图:

显然,ggplot 以某种方式改变了箱线图所基于的输入数据。然而,我的意图只是关注箱线图的一部分,以便我可以更仔细地检查各组之间的差异。我如何使用 ggplot 执行此操作?

我们将不胜感激您的建议。

不要使用您的 scale_y_continuous() 代码,而是使用 coord_cartesian(),如下所示。

这个

scale_y_continuous(breaks =seq(0, .05, .01), limit = c(0, 0.05))

替换为

coord_cartesian(ylim = c(0,0.05))

还注意到您试图表达意思。请注意,箱线图显示的不是平均数。也许您应该在数据展示时牢记一些事情。此外,箱线图通常优于其他选项,因为它显示数据分布(例如离群值)和其他重要统计数据以供比较。裁剪仅显示中位数,因此可能不是一个好主意,而您只能使用 geom_point() 显示中位数。