首页 > 解决方案 > 箱线图:Matlab 显示关于 R 的不同图形?

问题描述

我绘制了一个简单的数据矩阵

39  135 249 1   91  8   28  0   0   74  17  65  560
69  0   290 26  254 88  31  0   18  53  4   63  625
66  186 344 0   9   0   0   0   18  54  0   74  554
80  41  393 0   0   0   2   0   6   51  0   65  660
271 112 511 1   0   274 0   0   0   0   16  48  601
88  194 312 0   110 0   0   0   44  13  2   76  624
198 147 367 0   15  0   0   3   9   44  3   39  590

使用标准箱线图(即胡须从 Q1 和 Q3 扩展 1.5 x IRQ)。每列是一个变量,每一行是一个观察值。

尽管如此,我还是使用 R (RStudio 1.0.44) 和 Matlab2018 获得了两个不同的图形。特别是,晶须以不同的方式延伸。

在 Matlab 中,我使用以下代码:

% clearing workspace
clear all;
close all;
clc;

%entering in current directory where I find the txt data file 
tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));
clear tmp;

%reading data
df = readtable('pippo.txt', 'Delimiter', '\t', 'ReadVariableNames',false);
df = table2array(df)

figure(1);
boxplot(df(:, 1:end-1), 'Whisker', 1.5);
ylim([0 600]);

这会产生以下图表: 在此处输入图像描述

在 R 中,我使用以下代码:

rm(list = ls())

# getting the current directory
working_dir <-dirname(rstudioapi::getActiveDocumentContext()$path)

# setting the working directory where I finf the txt file with data
setwd(working_dir)

df <- read.table("pippo.txt")
jpeg('r_boxplot.jpg')
boxplot(df[,1:12], las=2, ylim=c(0,600), range=1.5)
dev.off()

这会产生以下图表:

在此处输入图像描述

观察 1:如果我从两个脚本中省略参数 'whiskers' 和 'range' 我会得到相同的图形;预计 1.5 似乎是默认的胡须值。

观察 2:matlab 和 R 似乎都以正确的方式读取数据,我的意思是两个工作区都可视化相同的矩阵

我错过了什么?我应该相信哪个图表?

标签: rmatlabboxplot

解决方案


R箱线图代码的解释

箱线图的 MATLAB 代码

因此,通过这两个函数,我发现它们似乎都在计算完全相同的东西,即使它们如何定义 IQR

R声称正在为箱线图执行以下操作

upper whisker = min(max(x), Q_3 + 1.5 * IQR)
lower whisker = max(min(x), Q_1 – 1.5 * IQR)
where IQR = Q_3 – Q_1, the box length.

MATLAB 声称为他们的箱线图这样做

p75 + w(p75 – p25) 
p25 – w(p75 – p25)
where p25 and p75 are the 25th and 75th percentiles, respectively.

即使他们定义胡须扩展的方式与 Matlab 说明的相同

%   The plotted whisker extends to the adjacent value, which is the most 
%   extreme data value that is not an outlier. Set whisker to 0 to give 
%   no whiskers and to make every point outside of p25 and p75 an outlier.

和 R 状态

Range determines how far the plot whiskers extend out from the box. If range is 
positive, the whiskers extend to the most extreme data point which is no more than 
range times the interquartile range from the box. A value of zero causes the whiskers 
to extend to the data extremes.

就个人而言,我觉得这与执行计算的一些基本方式有关。编辑在弄乱代码之后,我可以确认它与底层计算有关。

R代码

quantile(a,c(.25, .75))
25% 75% 
301 380 
> 380+1.5*(380-301)
[1] 498.5
> 301-1.5*(380-301)
[1] 182.5

Matlab代码

prctile(te,[25,75])
ans =

  295.5000  386.5000

W75 = p75 + 1.5*(p75-p25)
W25 = p25 - 1.5*(p75-p25)

W75 =

   523


W25 =

   159

我使用您数据的第三列来测试并查看如何计算分位数。如您所见,25% 和 75% 差别不大,只是差别足以导致 matlab 代码中的晶须截止值更大。


推荐阅读