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

20 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Benjamin Larin
Benjamin Larin el 15 de Nov. de 2019
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.

Más respuestas (1)

the cyclist
the cyclist el 14 de Nov. de 2019
For what it is worth, this is not a bug. It is a change that was documented in the release notes for R2019b. It's in the Graphics section for that page:
"Stacked groups of bars display negative bars below zero, rather than overlapping the bars."
I don't think you have any choice but to reprogram your algorithm based on the new behavior.

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by