How to add percent change in barplot?

25 ビュー (過去 30 日間)
Daphne PARLIARI
Daphne PARLIARI 2021 年 1 月 4 日
コメント済み: Daphne PARLIARI 2021 年 1 月 4 日
Hello everyone and happy new year!
I have a barplot (average deaths per degree of temperature, 30-37oC) to which I want to add the percentage change from bar to bar. Attached you can find the excel file I am proccessing and here is the part of code that produces tha barplot.
Is there an efficient way to do so?
Thanks in advance!
PS. I am on R2019a.
Daily_Data = readtable('Daily_Data_MoT.xlsx');
idx = Daily_Data.Daily_T(:) > 30;
Daily_Data_new = Daily_Data(idx,:);
[G, Temperature] = discretize(Daily_Data_new.Daily_T, 30:37);
d_mean = accumarray(G, Daily_Data_new.Daily_Deaths, [length(Temperature), 1], @mean);
bar(Temperature, d_mean); xlabel('T (oC)'); ylabel('Average deaths');

採用された回答

Steve Eddins
Steve Eddins 2021 年 1 月 4 日
編集済み: Steve Eddins 2021 年 1 月 4 日
If you want text labels instead of a line plot (Cris' suggestion), then try this code. It gets the Bar object as the output argument from bar, and then computes the percent change and where to put the labels using the XData and YData properties of the Bar object.
b = bar(Temperature, d_mean); xlabel('T (oC)'); ylabel('Average deaths');
x = b.XData;
y = b.YData;
percent_change = 100 * diff(y) ./ y(1:end-1);
for k = 1:length(percent_change)
text(x(k+1),y(k+1),sprintf('%0.1f%%',percent_change(k)),...
'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
end
  3 件のコメント
Steve Eddins
Steve Eddins 2021 年 1 月 4 日
reference_temp = y(1); % 30oC in plot
percent_change = 100 * (y - reference_temp) / reference_temp;
Daphne PARLIARI
Daphne PARLIARI 2021 年 1 月 4 日
With this code below
x = b.XData;
y = b.YData;
reference_temp = y(1); % 30oC in plot
percent_change = 100 * (y - reference_temp) / reference_temp;
for k = 1:length(percent_change)
text(x(k+1),y(k+1),sprintf('%0.1f%%',percent_change(k)),...
'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
end
I am getting the Error: Index exceeds the number of array elements (8).

サインインしてコメントする。

その他の回答 (1 件)

Cris LaPierre
Cris LaPierre 2021 年 1 月 4 日
You can add a line plot to a bar plot. Just use the hold on command.
If you need it to be on a separate Y scale, look at this example
  1 件のコメント
Daphne PARLIARI
Daphne PARLIARI 2021 年 1 月 4 日
Thank you Cris! Since I am not very experienced in MatLab, Steve's answer was easier for me to comprehend...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by