Exclude NaN values when plotting using bar3
13 views (last 30 days)
Show older comments
I want to create a 3d bar plot which only shows bars in locations with real values (not NaNs). Unfortunately, when I try to do this, the plot includes a bar of height zero in each location where there's a NaN. I want no bar at all - just a blank space. Can anybody help?
clear; close all; clc
S = [37,46];
loads = [nan, 1.62, 1.85, nan;
0.88, nan, 0.85, 0.62];
figure()
bar3(S,loads)
xticks([1,2,3,4])
xticklabels({'14','15','17.5','21'})
xlabel('H, mm')
ylabel('S, mm')
zlabel('Pull-off Force, N')
Output:

1 Comment
Rik
on 29 Apr 2020
You may need to plot each bar separately. The bar3 function returns a 1x4 surface object when I run your code, so you can't simply delete some patch objects, as I had hoped.
Accepted Answer
Ameer Hamza
on 29 Apr 2020
Edited: Ameer Hamza
on 30 Apr 2020
Edit: This code is a more general and does not require to set the edge color to white
clear; close all; clc
S = [37,46];
loads = [nan, 1.62, 1.85, nan;
0.88, nan, 0.85, 0.62];
fig = figure();
ax = axes();
hold(ax);
grid(ax);
view(3);
b = gobjects(size(loads));
for i=1:size(loads,2)
for j=1:size(loads,1)
if ~isnan(loads(j,i))
b(j,i) = bar3(S(j), loads(j,i), 5);
b(j,i).CData(:) = i;
b(j,i).XData = rescale(b(j,i).XData, 0.6, 1.4) + i - 1;
end
end
end
ax.CLim = [1 size(loads, 2)];
ax.YDir = 'reverse';
ax.XTick = 1:size(loads,2);
xticklabels({'14','15','17.5','21'})
ax.YTick = S;
axis(ax, 'tight');
ax.YLim = ax.YLim + [-2 2];
xlabel('H, mm')
ylabel('S, mm')
zlabel('Pull-off Force, N')

Try this. The downside of this method is that it cannot remove the edges of the individual bar, so It set the color of all the edges to white so that the edges on the ground seem invisible.
clear; close all; clc
S = [37,46];
loads = [nan, 1.62, 1.85, nan;
0.88, nan, 0.85, 0.62];
fig = figure();
b = bar3(S,loads);
xticks([1,2,3,4])
xticklabels({'14','15','17.5','21'})
xlabel('H, mm')
ylabel('S, mm')
zlabel('Pull-off Force, N')
[b.EdgeColor] = deal('w');
[r,c] = find(isnan(loads));
for i=1:numel(r)
r_ = r(i);
c_ = c(i);
b(c_).CData(6*(r_-1)+1:6*r_, :) = nan;
end

4 Comments
Ameer Hamza
on 30 Apr 2020
I am glad to be of help.
No, the edge color cannot be set individually. Each surface object has a single EdgeColor property.
Ameer Hamza
on 30 Apr 2020
I have updated my answer to show a more general way, which does not require setting the edge color to white. Each bar is a seperate surface object.
More Answers (0)
See Also
Categories
Find more on 2-D and 3-D Plots 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!