how to plot different horizontal lines over each group of bar plot

9 ビュー (過去 30 日間)
priyam kar
priyam kar 2023 年 12 月 8 日
コメント済み: Dyuman Joshi 2023 年 12 月 8 日

採用された回答

Star Strider
Star Strider 2023 年 12 月 8 日
編集済み: Star Strider 2023 年 12 月 8 日
Try something like this —
A = (5+rand(10))/6;
figure
hb = bar(A);
for k = 1:numel(hb)
xep(k,:) = hb(k).XEndPoints;
end
L = min(xep);
R = max(xep);
hold on
plot([L(:) R(:)], [1 1]*0.75, '-k', 'LineWidth',3)
hold off
figure
hb = bar(A);
for k = 1:numel(hb)
xep(k,:) = hb(k).XEndPoints;
end
L = min(xep);
R = max(xep);
hold on
plot([L(:) R(:)], [1 1]*0.75, '-k', 'LineWidth',3)
hold off
xlim([0.5 2.5])
Make appropriate changes to get the result you want.
EDIT — (8 Dec 2023 at 13:43)
To extend the lines to cover all the bars in each group (rather than stopping at the midpoints), use the normalised ‘Barwidth’ data as well to extend it —
A = (5+rand(10))/6;
figure
hb = bar(A);
BW = hb.BarWidth
BW = 0.8000
for k = 1:numel(hb)
xep(k,:) = hb(k).XEndPoints;
end
L = min(xep);
R = max(xep);
hold on
plot([L(:) R(:)]+[-0.5 0.5]*BW/numel(hb), [1 1]*0.75, '-k', 'LineWidth',3)
hold off
figure
hb = bar(A);
BW = hb.BarWidth;
for k = 1:numel(hb)
xep(k,:) = hb(k).XEndPoints;
end
L = min(xep);
R = max(xep);
hold on
plot([L(:) R(:)]+[-0.5 0.5]*BW/numel(hb), [1 1]*0.75, '-k', 'LineWidth',3)
hold off
xlim([0.5 2.5])
.
  2 件のコメント
priyam kar
priyam kar 2023 年 12 月 8 日
Thank you for help, worked perfectly
Star Strider
Star Strider 2023 年 12 月 8 日
As always, my pleasure!

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

その他の回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2023 年 12 月 8 日
Here's a demo -
%Random data
mat = randi([11 19], 4, 6);
%Bar plot
b = bar(mat);
hold on
%Get the x-coordinates of each group (center of each bar)
%Each column represents the x-coordinates of each bar group
x = vertcat(b.XEndPoints)
x = 6×4
0.6667 1.6667 2.6667 3.6667 0.8000 1.8000 2.8000 3.8000 0.9333 1.9333 2.9333 3.9333 1.0667 2.0667 3.0667 4.0667 1.2000 2.2000 3.2000 4.2000 1.3333 2.3333 3.3333 4.3333
%Get the coordinates of the end points
x = x([1 end],:).'
x = 4×2
0.6667 1.3333 1.6667 2.3333 2.6667 3.3333 3.6667 4.3333
plot(x, [5 5], 'LineWidth', 2.5, 'Color', 'k');
hold off
  2 件のコメント
priyam kar
priyam kar 2023 年 12 月 8 日
Thank you very much for your help, your solution also works perfectly, however i used the other solution provided by Mr. Star Strider. Thank you once again
Dyuman Joshi
Dyuman Joshi 2023 年 12 月 8 日
You are welcome!

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

カテゴリ

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

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by