Matlab绘制柱状图,不使用bar函数,设置每个柱的颜色。
patch
函数绘制面积图,此时,每个矩形的四个顶点分别为 (x, 0), (x + step, 0), (x, y), (x + step, y)
,同时通过 patch
函数来设置不同的颜色;Matlab参考代码如下:
(注:在本demo中,绘制10个柱子,关于原点对称,大家可以根据自己的需求自行修改)。
%%
clc;
clear;
%%
% 设置颜色
clrs = [
7, 45, 115;
14, 83, 153;
45, 122, 181;
84, 158, 204;
144, 191, 224;
245, 189, 169;
240, 144, 113;
217, 96, 85;
186, 55, 50;
148, 19, 41
];
clrs = clrs / 255.0;
%%
ks = [1.621, 0.540, 2.162, 10.811, 28.648, 35.135, 12.972, 4.864, 1.081, 2.162];
figure(1);
gc = get(gca);
set(gcf, 'position', [0, 50, 750, 600]);
set(gca, 'FontName', 'Arial', 'FontSize', 20);
xlabel('X', 'FontSize', 24, 'FontName', 'Arial');
ylabel('Y', 'FontSize', 24, 'FontName', 'Arial');
hold on;
% 设置步长
step = 2.5;
% 使用patch函数绘制图像
for i = 1 : length(ks)
x = [i, i + 1, i + 1, i];
x = (x - 6) * step;
y = [0, 0, ks(i), ks(i)];
spi = patch(x, y, clrs(i, :), 'FaceA', .85, 'EdgeA', 0);
text(x(1) + 0.35, ks(i) + 1.5, ...
num2str(ks(i), '%.1f'),...
'ROtation', 0, 'color', clrs(i, :), ...
'FontSize', 20, 'FontName', 'Arial');
end
% 设置xy轴范围以及显示的刻度等
xlim([-12.5 12.5]);
ylim([0 floor(max(ks(:) + 10) / 10) * 10]);
set(gca, 'xtick', [-10 -7.5 -5 -2.5 0 2.5 5 7.5 10]);
set(gca, 'ytick', [0 : 10 : 70]);
set(gca, 'xTickLabel', num2str(get(gca,'xTick')', '%.1f'));
hold on;
rr = axis;
plot(rr(1:2), [rr(4), rr(4)], 'k-', [rr(2), rr(2)], rr(3:4), 'k-');
set(gca, 'looseInset', [0.12, 0.03, 0.03, 0.08]);