diff --git a/test_cases/testviolinplot.m b/test_cases/testviolinplot.m new file mode 100644 index 0000000..6047002 --- /dev/null +++ b/test_cases/testviolinplot.m @@ -0,0 +1,21 @@ + +% TEST CASE 1 +display('Test 1: Violin plot default options'); +load carbig MPG Origin +Origin = cellstr(Origin); +figure +vs = violinplot(MPG, Origin); +ylabel('Fuel Economy in MPG'); +xlim([0.5, 7.5]); + +display('Test 1 passed ok'); + +% TEST CASE 2 +display('Test 2: Test the plot ordering option'); +grouporder={'USA','Sweden','Japan','Italy','Germany','France','England'}; + +figure; +vs2 = violinplot(MPG,Origin,'GroupOrder',grouporder); +display('Test 2 passed ok'); + +%other test cases could be added here diff --git a/violinplot.m b/violinplot.m index 6b4fba3..c151312 100644 --- a/violinplot.m +++ b/violinplot.m @@ -44,11 +44,27 @@ % Defaults to false % 'ShowMean' Whether to show mean indicator % Defaults to false +% 'GroupOrder' Cell of category names in order to be plotted. +% Defaults to alphabetical ordering % Copyright (c) 2016, Bastian Bechtold % This code is released under the terms of the BSD 3-clause license hascategories = exist('cats','var') && not(isempty(cats)); + + %parse the optional grouporder argument + %if it exists parse the categories order + % but also delete it from the arguments passed to Violin + grouporder = {}; + idx=find(strcmp(varargin, 'GroupOrder')); + if ~isempty(idx) && numel(varargin)>idx + if iscell(varargin{idx+1}) + grouporder = varargin{idx+1}; + varargin(idx:idx+1)=[]; + else + error('Second argument of ''GroupOrder'' optional arg must be a cell of category names') + end + end % tabular data if isa(data, 'dataset') || isstruct(data) || istable(data) @@ -73,7 +89,12 @@ % 1D data, one category for each data point elseif hascategories && numel(data) == numel(cats) - cats = categorical(cats); + if isempty(grouporder) + cats = categorical(cats); + else + cats = categorical(cats, grouporder); + end + catnames = categories(cats); for n=1:length(catnames) thisCat = catnames{n};