How to change the xticketlabe of a bar chat

조회 수: 1 (최근 30일)
Yaser Khojah
Yaser Khojah 2021년 1월 27일
댓글: Yaser Khojah 2021년 1월 27일
I have two matrixes (x and y) that I want to plot using the bar chart.
i just want to make the first bar in the plot on zero instead of 1, the next one one 1 and so on. In addition, how to make these bars wider, while keeping them sepearte. Anyway to change the bar color according to an index matrix? Could you please help.
Moreover, anyway to present this better as showing a timeline goes from year 0 to year 20 in the x-axis. Then, each bar showing the field that start in the same year. For example, in the first bar, I have three fields that start on the same day as Field 1, 2 and 8. In my plot in the first year or bar, I have them but not sure how to make them presented better as saying "Field1, Field 2 and Field 8)
x = 0:20; % the time horizon
A = repmat(x,3,1);
% y name of the field that start on the year. For example Field 1 start in year zero, Field 2 start in year 0; Field 8 in year zero; etc
y = 1 0 0 0 0 0 0 0 3 0 6 7 0 0 4 0 0 0 5 0 0
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
figure
bar(y','stacked');
xlabel('Years')
ylabel('Field Name')
xlim([0 20])

채택된 답변

dpb
dpb 2021년 1월 27일
You can either just set xticks where you want them or use the x vector in bar if there are other than just ordinal positions for the bars. You use the optional third positional parameter, width to set the bar width; it is a fraction of the available width with a default of 0.8 (80% coverage).
It isn't really clear about the "Field" and the number as being the bar height what that represents nor what is wanted; it seems somewhat peculiar from the description.
x=1:size(y,2);
hBar=bar(x,y',1,'stacked');
xticks(x)
xlim([x(1) x(end)]+[-0.5 0.5])
legend("Field "+[1:size(y,1)].')
produces the following:
hTxt=arrayfun(@(i) text(hBar(i).XEndPoints,hBar(i).YEndPoints,num2str(hBar(i).YEndPoints.','%0.1f'), ...
'verticalalignment','bottom','horizontalalign','center','fontsize',6,'color','k'), ...
1:numel(hBar),'UniformOutput',false);
will label the top of each bar section; the above generic for all bars writes the zero elements as well; you would have to use logical tests to not include those; perhaps turning those elements that are zero to NaN so they'll not be plotted would be a better option.
The above uses all the space there is to be used with the number of bars you have defined; it would take again extra logic if one were to want to only place the nonzero elements onto the axis without the horizontal spacing for missing years.
  댓글 수: 1
Yaser Khojah
Yaser Khojah 2021년 1월 27일
Thank you so mcuh for your help. It is very useful and finally it is working.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by