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 Center および File ExchangeAnnotations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by