Can the BAR and BARH functions in MATLAB 7.0.1 (R14SP1) handle negative values when plotting a stacked graph?

2 visualizzazioni (ultimi 30 giorni)
I have the following matrix in MATLAB:
a = [1 2; 1 -1];
Plotting a bar graph of this data with either the BAR or BARH function as follows gives a counterintuitive result:
bar(a,'stack')
barh(a,'stack')
In the resulting plot, the negative value is drawn over the positive value, so on the plot it looks like there is only one value in the second row. I expect the negative values to be displayed on the negative side of the axis.

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 21 Mag 2013
The ability to display negative data values on the negative side of the axis when creating a stacked bar graph using BAR or BARH functions is currently not available in MATLAB.
As a work around, consider the following code
function barExtended(varargin)
% Create a stacked bar graph of both negative and positive values.
%
% Syntax.
% barExtended(Y)
% Create a new figure window and place the bar plot within it.
%
% barExtended(axes_handle,Y)
% Place the bar plot with the axes pointed to be axes_handle.
% Parse input.
if nargin == 1
Y = varargin{1};
else
Y = varargin{2};
end
% Positive components.
fh(1) = figure;
hP = bar(gca,Y.*(Y>0),'stacked');
ahP = gca;
% Negative components.
fh(2) = figure;
hN = bar(Y.*(Y<0),'stacked');
% Clean up.
if nargin == 1
set([hP,hN],'parent',ahP);
delete(fh(2));
else
set([hP,hN],'parent',varargin{1});
delete(fh);
end
end
Following is an illustrative example:
barExtended(rand(5)-rand(5))
As another possible workaround you can also use the function BARX attached with this solution.
  1 Commento
Walter Roberson
Walter Roberson il 15 Giu 2017
Nikolay Iskrev comments,
This solution doens't work if one wants to add a legend to the plot. It is very disappointing that we have to use crude hacks like this one to make a basic bar chart in matlab.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su 2-D and 3-D Plots in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by