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

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
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...

카테고리

도움말 센터File Exchange에서 Annotations에 대해 자세히 알아보기

제품

릴리스

R2024a

태그

편집:

dpb
2025년 2월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by