进阶版MATLAB 3D柱状图

Matlab 复制代码
%% 1. 数据准备
% 假设数据是一个任意形式的矩阵
% 例如:5行 x 7列的矩阵
data = [3 5 2 6 8 4 7;
        7 2 6 9 3 5 8;
        4 8 3 7 2 6 9;
        6 1 5 8 4 7 2;
        9 4 7 3 6 2 5];

% 定义行和列的标签(可选)
rowLabels = {'Row1', 'Row2', 'Row3', 'Row4', 'Row5'}; % 行标签
colLabels = {'Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7'}; % 列标签

%% 2. 颜色定义
% 十六进制颜色转换为RGB格式
colorsHex = {
    '#94c1b6', % 第一种颜色
    '#6b969a', % 第二种颜色
    '#dcc672', % 第三种颜色
    '#e0ba19', % 第四种颜色
    '#C69519', % 第五种颜色
};

% 将十六进制颜色转换为RGB
colorsRGB = cellfun(@(c) hex2rgb(c), colorsHex, 'UniformOutput', false);
colorsRGB = vertcat(colorsRGB{:});

% 创建一个渐变色
nPoints = 300;  % 渐变色的点数
map = zeros(nPoints, 3);  % 初始化渐变色矩阵

for i = 1:3
    map(:,i) = linspace(colorsRGB(1,i), colorsRGB(end,i), nPoints);  % 对每个颜色通道进行插值
end

% 显示渐变色条
figure;
imshow(repmat(map, [1, 10, 1]));
title('渐变色条');


%% 3. 绘制三维柱状图
figureHandle = figure('Color','w'); % 创建白色背景图形窗口
b = bar3(data, 0.5); % 绘制3D柱状图,0.5控制柱子宽度

% 添加标签
hTitle = title('3D Gradient Bar Plot');
hXLabel = xlabel('Columns');
hYLabel = ylabel('Rows');
hZLabel = zlabel('Values');

%% 4. 颜色渐变设置
for k = 1:length(b)
    zdata = b(k).ZData;        % 获取柱子高度数据
    b(k).CData = zdata;         % 将高度数据映射为颜色数据
    b(k).FaceColor = 'interp';  % 设置渐变填充
end
colormap(map)                   % 应用颜色映射
colorbar                        % 添加颜色标尺

%% 5. 坐标轴调整
set(gca, 'Box', 'off',...                          % 关闭边框
        'LineWidth', 1,...                         % 坐标轴线宽
        'GridLineStyle', '-',...                   % 网格线型
        'XGrid', 'off', 'YGrid', 'off','ZGrid', 'on',... % 显示Z轴网格
        'TickDir', 'out',...                       % 刻度朝外
        'TickLength', [.015 .015],...              % 刻度长度
        'XColor', [.1 .1 .1],...                  % 坐标轴颜色
        'YColor', [.1 .1 .1],...
        'ZColor', [.1 .1 .1],...
        'XTickLabel', colLabels,...                % 设置列标签
        'YTickLabel', rowLabels,...                % 设置行标签
        'FontSize', 10);                          % 坐标轴字号

% 调整视角
view(-45, 30) % 设置3D视图角度

%% 6. 字体设置
set([hXLabel, hYLabel, hZLabel],...
    'FontSize', 12, 'FontWeight', 'bold',...
    'FontName', 'Arial');
set(hTitle, 'FontSize', 14, 'FontWeight', 'bold');

%% 7. 图片输出
print(figureHandle, 'GradientBarPlot.png', '-r300', '-dpng');
disp('图片已保存为GradientBarPlot.png');

将十六进制颜色转换为 RGB 格式

给出的颜色是:

  • #94c1b6
  • #6b969a
  • #dcc672
  • #e0ba19
  • #C69519

我们将它们转换为 RGB 格式。然后,我们可以使用线性插值创建一个渐变色。

相关推荐
火山口车神丶24 分钟前
故障码循环显示专项--和Deepseek的一次深度交互
matlab
MoonBit月兔25 分钟前
双周报Vol.65:新增is表达式、字符串构造和数组模式匹配增强、IDE模式匹配补全增强...多项技术更新!
开发语言·ide·编程语言·moonbit
qq_441685751 小时前
bash shell笔记——循环结构
开发语言·bash
KAI77381 小时前
2月11日QT
开发语言·qt
论迹1 小时前
【JavaEE】-- 多线程(初阶)1
java·开发语言·网络·java-ee
沈清韵1 小时前
Lisp语言的软件工程
开发语言·后端·golang
S-X-S2 小时前
Java面试题-Spring Boot
java·开发语言·spring boot
ElseWhereR2 小时前
C++中函数的调用
开发语言·c++
Excuse_lighttime2 小时前
堆排序
java·开发语言·数据结构·算法·排序算法
arong_xu2 小时前
理解C++ Type Traits
开发语言·c++·type_traits