如何用MATLAB的violinplot在单X轴绘制两组分组小提琴图?
如何将分组小提琴图合并到单个X轴展示(MATLAB)
当前代码通过子图将两组均值对应的小提琴图分开展示,需求是将所有小提琴图合并到同一个X轴上,每组(对应一个均值)包含两个小提琴图,组间保持间距,最终效果为:X轴上有两个分组标签,每个标签下方对应两个并排的小提琴图。
原代码:
clear all close all % Create two column vectors of 10000 normally distributed random numbers with a % mean of 1 and a standard deviation of 10 and 5, respectively r1 = normrnd(1, 10,[10000,1]); r2 = normrnd(1, 5,[10000,1]); % Create two colum vectors of 10000 normally distributed random numbers with a % mean of 20 and a standard deviation of 10 and 5, respectively r3 = normrnd(20, 10,[10000,1]); r4 = normrnd(20, 5,[10000,1]); % Create a figure with two subplots figure; % First subplot subplot(1, 2, 1); hold on; ylim([-50, 70]); % set y-axis range so r1-r4 can all be plotted on same axis [f, xf] = kde(r1); violinplot('EvaluationPoints', xf, 'DensityValues', f); [f, xf] = kde(r2); violinplot('EvaluationPoints', xf, 'DensityValues', f); xticklabels('mean = 1'); hold off; % Second subplot subplot(1, 2, 2); hold on; ylim([-50, 70]); % set y-axis range so r1-r4 can all be plotted on same axis [f, xf] = kde(r3); violinplot('EvaluationPoints', xf, 'DensityValues', f); [f, xf] = kde(r4); violinplot('EvaluationPoints', xf, 'DensityValues', f); xticklabels('mean = 20') hold off;
修改方案
核心思路是在同一个坐标轴上,为每个小提琴图指定独立的X轴位置,通过调整位置实现分组并排效果,具体代码如下:
clear all close all % 生成数据 r1 = normrnd(1, 10,[10000,1]); r2 = normrnd(1, 5,[10000,1]); r3 = normrnd(20, 10,[10000,1]); r4 = normrnd(20, 5,[10000,1]); figure; hold on; ylim([-50, 70]); % 定义每组内两个小提琴的X位置,组间留足间距 x_pos_group1 = [1, 1.5]; x_pos_group2 = [3, 3.5]; % 绘制第一组(mean=1)的两个小提琴图 [f, xf] = kde(r1); violinplot('EvaluationPoints', xf, 'DensityValues', f, 'XData', x_pos_group1(1)); [f, xf] = kde(r2); violinplot('EvaluationPoints', xf, 'DensityValues', f, 'XData', x_pos_group1(2)); % 绘制第二组(mean=20)的两个小提琴图 [f, xf] = kde(r3); violinplot('EvaluationPoints', xf, 'DensityValues', f, 'XData', x_pos_group2(1)); [f, xf] = kde(r4); violinplot('EvaluationPoints', xf, 'DensityValues', f, 'XData', x_pos_group2(2)); % 设置X轴刻度与标签,刻度对应每组的中心位置 xticks([mean(x_pos_group1), mean(x_pos_group2)]); xticklabels({'mean = 1', 'mean = 20'}); % 调整X轴范围,避免图形边缘被截断 xlim([0.5, 4]); hold off;
关键说明
XData参数:为每个小提琴图指定X轴上的位置,实现同一组内两个图并排,组间用间距区分xticks与xticklabels:将刻度设置在每组的中心位置,对应分组标签,保证视觉上的分组对应关系xlim:调整X轴范围,让所有小提琴图都完整显示,同时保持合理的留白
内容的提问来源于stack exchange,提问作者user31119379
相关产品推荐
相关产品推荐

