How to draw a bar chart with a color gradient with matlab?

19 Ansichten (letzte 30 Tage)
Mang GAO
Mang GAO am 22 Jul. 2022
Kommentiert: Mang GAO am 24 Jul. 2022
Hello, everyone, I need draw a bar chart as the above figure. The following is the code I search from the internet, but it not works now. May be it works on a old Matlab version. Is there anyone can help me? Thank you so much.
%% 老版本的matlab是好用的
clear,clc;close all;
%% 用到的数据
%% 用到的数据
n = 13;
Z = rand(n,1);
%% 默认图片
bar(Z);
%% 更加漂亮的图片
% 图片会以渐变的方式着色,效果非常不错
figure
h=bar(Z);
ch = get(h,'Children');
fvd = get(ch,'Faces');
fvcd = get(ch,'FaceVertexCData');
[zs, izs] = sortrows(Z,1);
k = 128; % 准备生成128 *3 行的colormap
colormap(summer(k)); % 这样会产生一个128 * 3的矩阵,分别代表[R G B]的值
% 检视数据
whos ch fvd fvcd zs izs
%
% Name Size Bytes Class Attributes
%
% ch 1×1 8 double
% fvcd 66×1 528 double
% fvd 13×4 416 double
% izs 13×1 104 double
% zs 13×1 104 double
%
shading interp % Needed to graduate colors
for i = 1:n
color = floor(k*i/n); % 这里用取整函数获得color在colormap中行
row = izs(i); % Look up actual row # in data
fvcd(fvd(row,1)) = 1; % Color base vertices 1st index % here is the problem begin
fvcd(fvd(row,4)) = 1;
fvcd(fvd(row,2)) = color; % Assign top vertices color
fvcd(fvd(row,3)) = color;
end
set(ch,'FaceVertexCData', fvcd); % Apply the vertex coloring
set(ch,'EdgeColor','k')

Antworten (1)

Cris LaPierre
Cris LaPierre am 22 Jul. 2022
Bearbeitet: Cris LaPierre am 22 Jul. 2022
You might find this site helpful.
Here's a quick example. Note that I have to use bar3 since bar does not have an 'interp' option for FaceColor.
y = rand(10,1);
b = bar3(y);
colormap summer
b.FaceColor = "interp";
for a = 1:length(b)
b(a).CData = b(a).ZData;
end
clim([0 1])
view(-90,0)
% For comparison
figure
bar(y)
colormap summer
  2 Kommentare
Adam Danz
Adam Danz am 22 Jul. 2022
Ha! I was typing up the same answer!
For those folks implementing this at home, the 2D view in Cris' bar3 plot is the YZ plane, not the XY plane that we're using to seeing in 2D plots. That means if you want to change axis properties such as adding an axis label or changing the tick labels, the y-axis is the horizontal axis and the z-axis in the vertical axis.
Mang GAO
Mang GAO am 24 Jul. 2022
Hi, Dr. Cris LaPierre,
Thank you so much. it works.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by