【024】繪製帶有誤差線的柱狀圖
需求分析:繪製帶有誤差線的柱狀圖
單系列帶誤差線柱狀圖
多系列帶誤差線柱狀圖
也有一個開源函式 barweb 可用,連結如下:
完整程式碼
clear
;
clc
;
% 生成示例資料
m
=
5
;
n
=
3
;
x
=
1
:
m
;
y
=
rand
(
m
,
n
)
+
2
;
% 誤差限
neg
=
rand
(
m
,
n
);
pos
=
rand
(
m
,
n
);
% 單系列帶有誤差線的柱狀圖
figure
;
bar
(
x
,
y
(:,
1
));
hold
on
errorbar
(
x
,
y
(:,
1
),
neg
(:,
1
),
pos
(:,
1
),
‘LineStyle’
,
‘none’
,
‘Color’
,
‘k’
,
‘LineWidth’
,
2
);
hold
off
% 多系列帶有誤差線的柱狀圖
figure
;
% 繪製柱狀圖
h
=
bar
(
x
,
y
);
% 單獨設定第二個系列第二個柱子為藍色
h
(
1
,
2
)。
FaceColor
=
‘flat’
;
h
(
1
,
2
)。
CData
(
2
,:)
=
[
0
,
0
,
1
];
% 設定第一個系列為綠色
h
(
1
,
1
)。
FaceColor
=
[
0
,
1
,
0
];
% 獲取誤差線 x 值
xx
=
zeros
(
m
,
n
);
for
i
=
1
:
n
xx
(:,
i
)
=
h
(
1
,
i
)。
XEndPoints
‘
;
end
% 繪製誤差線
hold
on
errorbar
(
xx
,
y
,
neg
,
pos
,
’LineStyle‘
,
’none‘
,
’Color‘
,
’k‘
,
’LineWidth‘
,
2
);
hold
off
% 繪製圖例
legend
({
’A1‘
,
’A2‘
,
’A3‘
});
% 設定 x 軸標籤
set
(
gca
,
’XTickLabel‘
,
{
’label1‘
,
’label2‘
,
’label3‘
,
’label4‘
,
’label5‘
});
% 試試 barweb
figure
;
barweb
(
y
,
neg
,
1
,
{
’label1‘
,
’label2‘
,
’label3‘
,
’label4‘
,
’label5‘
});
Matlab 2020b 測試報錯,將 151 和 152 行程式碼註釋掉,換成 153 行 或者 154 行都可以正常執行,個人覺得靈活性較差。
【秘籍】
主要難點在於如何獲取誤差線橫座標值,檢視屬性後的值目標屬性為 XEndPoints;