Grouped Bar Plot with NaN GAP
Show older comments
Hey there,
i am having a problem concering grouped bar charts. When i have NaN or Zero values in the matrix, the Plot creates several Gaps between the bars with values.
How can i group the valued bars together without changing the colormap ?
Ty in advance.

3 Comments
Cris LaPierre
on 16 Feb 2021
This is the documented behavior of grouped bar charts. Each row of your array corresponds to a group, and each column is a series. Your data has therefore been split into 2 groups, indicated on the X axis, with 3 series in each group.
The white spaces in your data are caused by 1) the gap between your two groups and 2) The 2nd series in group 2 having a value of NaN. The white space is for the red bar.
What is it you were expecting?
Mario Malic
on 16 Feb 2021
I removed the answer as the colors are not the same and it's not a proper answer. You will have to create a vector with CData to match the colors, accounting for NaNs in vectors. This will cause also issues in legend displaying 5 entries, instead of 3.
bar(1, [1 2 3])
hold on
bar(2, [4 6])
dpb
on 16 Feb 2021
As Cris notes, this is documented behavior and I agree with his assessment this would generally be the expected behavior of zero data being shown where is in relationship to each group and consistent bar coloring across groups.
There is no indication in the MATLAB bar() function, however, of there being any difference between a NaN and a 0; and those may well be entirely different things in some contexts. Perhaps that's the OP's underlying issue here.
One solution might be to label the missing bar location with a text string <Missing> or somesuch; this is relatively easy now that TMW has provided the 'XEndPoints' property that lets one know where to write such text.
hB=bar(f); % OP's bar, save handles
hTxt=text(hB(2).XEndPoints(2),0.1,'<IsMissing>','Rotation',90,'Color',hB(2).FaceColor); % write for the one NaN
ylim([0 8])
results in

One obviously could write code to locate where NaN are in the input array for the general case if an idea were to suit.
Alternatively, if really do want to collapse the bars, then again a generalized routine to implement Mario's idea above is also doable; one there has to retrieve the colors of the full-size group to match those with the missing bar(s).
Accepted Answer
More Answers (0)
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

