Plot multiple values in a single bar in bar plot
1 次查看(过去 30 天)
显示 更早的评论
Lets say I have an array y1 = [1,3,5,7,9] and y2 = [2,4,6,8,10]. I want to make a barplot between these two where its a single bar for each. So bar for y1 goes to max value 9 but in the same bar i can see values 1,3,5 and 7 and similarily y2 bar goes to max value 10 but can see values 2,4,6 and 8. And they are both shown in the same position for x axis that is x = 1. How can I do this. It has to be a bar plot and not normal plot. Thank you.
1 个评论
Harald
2025-2-21
Hi,
it sounds like you are looking for something like this:
y1 = [1,3,5,7,9];
y2 = [2,4,6,8,10];
bar([y1(1), diff(y1); y2(1), diff(y2)], "stacked")
It is not clear to me how both bars are supposed to be at x = 1 without one covering the other. Perhaps, you can go into more detail there or provide a sketch of the desired outcome.
Best wishes,
Harald
回答(1 个)
dpb
2025-2-21
编辑:dpb
2025-2-22
bar can't do that alll by itself without some help, but one can coerce things into what (I think) you asked for...comments in line
y1 = [1,3,5,7,9];
y2 = [2,4,6,8,10];
dy1=diff([0 y1]); % stacked plots add pieces so use differences from origin
dy2=diff([0 y2]);
w=1.0; % set bars to full width so the two will abut each other
hB=bar([dy1;dy2],w,'stacked'); % and make a basic stacked plot
xticks(mean(xticks)) % bar() has two bars by default, [1 2] put a tick in middle
xticklabels(1) % and label it as "1"
Here's the harder part to display the actual data as bar endpoints rather than the differences...
% build a struct array y.Data of the two original datapoints to match bar()
y=arrayfun(@(y1,y2)struct('Data',[y1 y2]),y1,y2);
% and pass the hB X,Y locations, and y data arrays to text() each in turn...
arrayfun(@(h,y)text(h.XEndPoints,h.YEndPoints,string(y.Data), ...
'horizontal','center','vertical','top'),hB,y)
% now let's do something about the garish default color mapping...
set(hB,{'FaceColor'},{'flat'});
colormap(gcf,'summer')
for i=1:numel(hB), hB(i).CData=i; end
Other modifications as desired are possible, of course...
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!