代码美学3:RGB转化+MATLAB制作渐变色
RGB颜色转化器(转换成matlab可以读取的形式)
n = input('请输入 n:');
color_matrix = cell(1, n);
for i = 1:n
R = input('请输入 R 值:');
G = input('请输入 G 值:');
B = input('请输入 B 值:');
color_matrix{i} = [R/255, G/255, B/255];
end
color_matrix
调用函数:
n = 3; % 输入颜色个数
colors = {[0.913725490196078,0.356862745098039,0.435294117647059] [0.933333333333333,0.705882352941177,0.717647058823529] [0.949019607843137,0.678431372549020,0.450980392156863]};
createGradientHeatmap(n, colors);
函数:
function createGradientHeatmap(n, colors)
% 输入检查
if length(colors) ~= n
error('输入的颜色数量与n不一致!');
end
% 创建渐变色
gradientColors = zeros(200, 3); % 200行RGB颜色
for i = 1:n-1
startColor = colors{i};
endColor = colors{i+1};
% 插值计算当前段颜色
range = linspace(0, 1, ceil(200/(n-1)));
for j = 1:3
gradientColors((i-1)*ceil(200/(n-1)) + (1:length(range)), j) = ...
interp1([0 1], [startColor(j) endColor(j)], range);
end
end
gradientColors = gradientColors(1:200, :); % 确保200个渐变
% 创建20x10热力图矩阵
heatmapMatrix = reshape(1:200, [20, 10]);
% 绘制热力图
figure('Position', [100, 100, 800, 400]); % 设置画布大小
imagesc(heatmapMatrix);
colormap(gradientColors);
colorbar;
title('Gradient Heatmap');
axis equal tight;
% 添加黑色分割线
hold on;
[rows, cols] = size(heatmapMatrix);
for i = 1:rows+1
plot([0.5, cols+0.5], [i-0.5, i-0.5], 'k', 'LineWidth', 1); % 横向分割线
end
for j = 1:cols+1
plot([j-0.5, j-0.5], [0.5, rows+0.5], 'k', 'LineWidth', 1); % 纵向分割线
end
% 在热力图上添加数字标注,步长为0.5,数字竖着增加
step = 0.5; % 设置步长
number = 0.5; % 从0开始
for j = 1:cols % 按列递增
for i = 1:rows % 按行循环
% 在每个格子中添加数字
text(j, i, num2str(number, '%.1f'), 'Color', 'black', 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Middle');
number = number + step; % 递增步长
end
end
hold off;
% 保存高清图片
saveas(gcf, 'gradient_heatmap_with_lines_and_numbers_vertical.png');
disp('热力图已保存为gradient_heatmap_with_lines_and_numbers_vertical.png');
end
%示例调用
%n = 3; % 输入颜色个数
%colors = {[1, 0, 0], [0, 1, 0], [0, 0, 1]}; % 红-绿-蓝渐变
%createGradientHeatmap(n, colors);