Change color of diagonal bars (1,1), (2,2), (3,3)... in bar3
56 ビュー (過去 30 日間)
古いコメントを表示
I am plotting a 2D histogram where there are 7 bars in each axis. An example of the data is attached as N.
On this plot, I would like to be able to color the diagonal bars [e.g., (1,1), (2,2) ... (7,7)] green, while leaving the rest of the bars the the base color.
I've built the chart using:
[N, Xedges, Yedges] = histcounts2(Xvals, yVals, [7, 7]);
h = bar3(N);
And I'm trying to color the bars using something like this, but I can't seem to figure out how to select the only the kth bar in each row:
for k = 1 : length(h) % operate on each row of bars
% Set FaceColor to 'flat' to use CData for coloring
h(k).FaceColor = 'flat';
set(h(k),'facecolor',[0 1 0]) % green
end
Ideally, I'd like to color both the top and sides of the selected bars green.
0 件のコメント
採用された回答
dpb
2025 年 9 月 3 日 16:32
編集済み: dpb
2025 年 9 月 3 日 17:30
load N
%[N, Xedges, Yedges] = histcounts2(Xvals, yVals, [7, 7]);
h = bar3(N)
h(1)
There is only one surface per row so there is no way to address the individual surfaces by the top-level handles; you would have to delve into the underlying CData arrays and set the correct set.
The colors are color order, not rgb triplets by default as well so
[h(1).CData(1,:);h(2).CData(1,:);h(6).CData(1,:);h(7).CData(1,:)]
You can poke at the CData array; there are six faces per bar so
figure
subplot(1,2,1)
h = bar3(N);
subplot(1,2,2)
h = bar3(N);
for i=1:7
offset=6*(i-1);
h(i).CData([1:6]+offset,:)=5;
end
changes all the faces of the diagonal bar to the color of the 5th bar initially which happens to be green. One would have to delve into the depths of the X|YData to figure out just which faces are which in the sections; I'm not sure of the storage order.
I'd have to do a lot of digging into the colormap and all to figure out how, precisely, one could manage to get to an rgb color or specific color in the mapping -- that's been an area I've never really figured out the inards of.
ADDENDUM
I've complained "since forever" that the bar and bar3 functions are weak sisters -- not being able to address each bar individually at the user level as desired here is a real weakness as is the fact you can't even set the X dimension vector.
10 件のコメント
dpb
2025 年 9 月 5 日 21:25
OK, glad to have been able to help...as we have noted, unfortunately there's only so much one can do with bar3 itself; getting more would require writing one's own replacement.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Distribution Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!