手搓箱图并输出异常值(MATLAB)
看下需求
想要复刻这种箱图,咱们直接开始手搓
%% 可修改
% 生成模拟数据(假设5个用户群体的发帖数)
data = {randn(100,1)*10 + 30, ... % 核心用户randn(200,1)*5 + 10, ... % 边缘用户randn(150,1)*8 + 20, ... % 积极社交用户randn(80,1)*12 + 25, ... % 潜在创意用户randn(120,1)*6 + 15}; % 积极创新用户
groups = {'用户等级','发布的贴子数','发帖频率','点度中心度','提案数'};%%
% 合成用于 boxplot 的向量
allData = vertcat(data{:});
groupIdx = [ones(100,1);2*ones(200,1);3*ones(150,1);4*ones(80,1);5*ones(120,1)];% 绘制箱图
figure;
boxplot(allData, groupIdx, 'Labels', groups);
title('分布箱图(含异常值)');
ylabel('数值');
grid on;% 识别并显示各组的异常值
for i = 1:numel(data)d = data{i};Q1 = prctile(d, 25);Q3 = prctile(d, 75);IQR = Q3 - Q1;lowerFence = Q1 - 1.5 * IQR;upperFence = Q3 + 1.5 * IQR;outliers = d(d < lowerFence | d > upperFence);if isempty(outliers)fprintf('组 “%s” 无异常值。\n', groups{i});elsefprintf('组 “%s” 的异常值 (%d 个):\n', groups{i}, numel(outliers));disp(outliers');end
end
小伙伴们可根据需要修改上方的数据
看下效果
Over!