MATLAB: Bar plot with negative and positive values, stacked, and with non-zero base value

bar plotbasevalueMATLABplotr2019b

In R2019a this used to work, but now the same code produces a wrong graph in R2019b. Here is a mwe:
close all; clear all; clc;
set(0,'defaultlinelinewidth',5)
% create data
basevalue = 10;
rng(4);
x = -1 + 2*rand(4,3);
% stack positive parts
pos_x = x;
pos_x(pos_x<0) = nan;
b1 = bar([ones(4,1)*basevalue, pos_x], 'stacked', 'BaseValue', basevalue);
set(b1, {'FaceColor'}, {[1 1 1]; 'r'; 'b'; 'y'});
hold on
% stack negative parts
neg_x = x;
neg_x(neg_x>0) = nan;
b2 = bar([ones(4,1)*basevalue, neg_x], 'stacked', 'BaseValue', basevalue);
set(b2, {'FaceColor'}, {[1 1 1]; 'r'; 'b'; 'y'});
hold on
% add line plot
p = plot(basevalue + sum(x,2));
p(1).Color = 'black';
hold off
The sum of the bars plus basevalue (10 in this graph) should be equal to the black line (a bar below 10 is to be considered negative). That's only the case when only positive values are stacked (3 on the x-axis). Setting basevalue to 0 gives also the correct result:
The graph was correct in my more extensive code under R2019a, now I started to repeat the same for another dataset and struggled for hours, until I realized that it seems to be a bug in R2019b.
Any idea for a good workaround?
Thanks,
Ben

Best Answer

As the cyclist said, I have to adjust my algorithm to R2019b. They solution is to use two y axes. Here's the code
close all; clear all; clc;
% create data
basevalue = 10;
rng(4);
x = -1 + 2*rand(4,3);
% bar plot
yyaxis left
b1 = bar(x, 'stacked');
set(b1, {'FaceColor'}, {[51 153 255]/255; [204 229 255]/255; [0 76 153]/255});
y_left = [-2 3];
axis([-inf inf y_left]);
% line plot
yyaxis right
p = plot(basevalue + sum(x,2));
p(1).Color = 'red';
axis([-inf inf y_left + basevalue]);
which produces
untitled.jpg
I have also to admit: Stacking negative with positive values is actually easier in R2019b.