✅作者简介:热爱科研的Matlab仿真开发者,修心和技术同步精进,
代码获取、论文复现及科研仿真合作可私信。
🍎个人主页:Matlab科研工作室
🍊个人信条:格物致知。
更多Matlab完整代码及仿真定制内容点击👇
🔥 内容介绍
在数据分析和可视化中,图表视化是一种非常有用的工具。通过图表视化,我们可以更直观地理解数据之间的关系和趋势。在Matlab中,我们可以通过简单的代码实现图表视化,并且可以使用颜色渐变来显示相关值的强度。
在本文中,我们将介绍如何使用Matlab实现图表视化相关矩阵,并将相关值显示为左下角的热图。首先,让我们来看看如何生成相关矩阵。在Matlab中,我们可以使用corr函数来计算相关矩阵。例如,我们可以使用以下代码生成一个随机的相关矩阵:
data = randn(100, 3); % 生成随机数据
corrMatrix = corr(data); % 计算相关矩阵
一旦我们有了相关矩阵,我们就可以使用图表视化来展示相关值的强度。我们可以使用热图来显示相关值,其中颜色的深浅表示相关值的强度。在Matlab中,我们可以使用heatmap函数来实现热图的可视化。以下是一个简单的示例代码:
heatmap(corrMatrix, 'Colormap', 'jet', 'ColorLimits', [-1, 1]); % 使用jet颜色映射,并设置颜色范围为-1到1
通过这段代码,我们可以将相关矩阵可视化为一个热图,并且使用颜色渐变来指示相关值的强度。这样,我们可以更直观地理解数据之间的关系,并且可以快速发现相关性较强的数据。
除了热图之外,Matlab还提供了许多其他图表视化的工具,如散点图、折线图、柱状图等。通过这些工具,我们可以更全面地分析和理解数据,为我们的工作和决策提供更多的参考和支持。
总之,图表视化是数据分析中非常重要的一环,通过Matlab,我们可以轻松实现相关矩阵的图表视化,并使用颜色渐变来指示相关值的强度。希望本文对你有所帮助,谢谢阅读!
📣 完整代码
function [ defaultColors ] = getdefaultcolors(n)if(nargin < 1)n = 0;enddefaultColors = [0 0.447 0.741; 0.85 0.325 0.098; ...0.929 0.694 0.125; 0.466 0.674 0.188; 0.301 0.745 0.933; ...0.494 0.184 0.556; 0.635 0.078 0.184];other_colors = [0 0.3793 0.1379;1.0000 0.0345 0.6897;0.1034 1.0000 0;0 0.2069 0.1724;0.5172 0.1724 1.0000;0.9310 1.0000 0;0.2069 0.1724 0.1724;0 0.1034 0.3448;0.7931 0 0.3448;1.0000 0.1034 0.9310];defaultColors = [defaultColors; other_colors];if(n > size(defaultColors, 2))clr = distinguishable_colors(n - size(defaultColors, 1), [defaultColors; 0 0 0; 1 1 1], @(x) colorspace('RGB->HSV',x));defaultColors = [defaultColors; clr];endend
function[width, height] = measureText(txt, opt, axis)if(nargin < 3)axis = gca();endhTest = text(axis, 0, 0, txt, opt);textExt = get(hTest, 'Extent');delete(hTest);height = textExt(4); %Heightwidth = textExt(3); %Widthend
%% Prepare the data% Load the example dataset and compute correlation matrixD = load('patients.mat');D.IsFemale = ismember(D.Gender, 'Female');[~, D.HealthStatus] = ismember(D.SelfAssessedHealthStatus, {'Poor', 'Fair', 'Good', 'Excellent'});% Prepare the matrixX = [D.IsFemale, D.Age, D.Weight, D.Height, D.Smoker, ...D.Systolic, D.Diastolic, D.HealthStatus];axislabels = {'GenderFemale', 'Age', 'Weight', 'Height', ...'IsSmoker', 'Systolic', 'Diastolic', 'HealthStatus'};C = corr(X);%% Draw the correlogram% Prepare the figure and set the sizefigure(1); clf();set(gcf, 'Position', [0 0 640 480]); movegui('center');% Draw the figurecorrelogram(C, 'AxisLabels', axislabels);set(gca, 'FontSize', 12)
function [] = correlogram(C, varargin)warning('off', 'MATLAB:polyshape:repairedBySimplify');p = inputParser;validX = @(x) validateattributes(x, {'cell', 'numeric', 'logical'}, ...{'2d', 'nonempty', 'real', '<=', 1, '>=', -1});validScalar = @(x) validateattributes(x, {'logical', 'numeric'}, ...{'scalar','nonempty','real','nonnan'});validColorArray = @(x) validateattributes(x, {'numeric'}, ...{'2d', 'nonempty', 'real', 'nonnan', 'ncols', 3});addRequired(p, 'C', validX);addParameter(p, 'AxisLabels', [], @iscell);addParameter(p, 'Labels', [], @iscell);addParameter(p, 'cMin', -1, validScalar);addParameter(p, 'cMax', 1, validScalar);addParameter(p, 'colorMin', [0 0 1], validColorArray);addParameter(p, 'colorZero', [1 1 1]*0.96, validColorArray);addParameter(p, 'colorMax', [1 0 0], validColorArray);addParameter(p, 'numDigits', 2, @isnumeric);addParameter(p, 'boxWidthRatio', 1, validScalar);addParameter(p, 'boxHeightRatio', 1, validScalar);addParameter(p, 'BoxLineWidth', 0.5, validScalar);addParameter(p, 'RadiusRatio', 0.9, validScalar);addParameter(p, 'Colors', [], @isnumeric);addParameter(p, 'VariableNames', cell(length(C), 1), @iscell);addParameter(p, 'ShowDiagonal', false, @islogical);addParameter(p, 'FontSize', [], validScalar);addParameter(p, 'Sorting', true, @islogical);addParameter(p, 'XDir', 'normal', @ischar);addParameter(p, 'YDir', 'reverse', @ischar);parse(p, C, varargin{:});param = p.Results;checkUsingDefaults = @(p,varname) any(strcmp(p.UsingDefaults,varname));[nRow, nColumn] = size(C);if((nRow == nColumn) && param.Sorting)for i = 1:2Z = linkage(C, 'average');D = pdist(C);si = optimalleaforder(Z, D);C = C(si, si);if(~isempty(param.AxisLabels))param.AxisLabels = param.AxisLabels(si);param.VariableNames = param.VariableNames(si);endendendif(checkUsingDefaults(p, 'Labels'))labels = cell(size(C));for iRow = 1:nRowfor iColumn = 1:nColumncValue = C(iRow, iColumn);labels{iRow, iColumn} = num2str(cValue, ['%.', num2str(param.numDigits), 'f']);if(iRow == iColumn); labels{iRow, iColumn} = param.VariableNames{iRow}; endendendparam.Labels = labels;endif(checkUsingDefaults(p, 'Colors'))colorMin = param.colorMin;colorZero = param.colorZero;colorMax = param.colorMax;cols = color_spacing_continuous(C(:), [param.cMin; 0; param.cMax], [colorMin; colorZero; colorMax]);param.Colors = reshape(cols, nRow, nColumn, 3);endbox_width_ratio = param.boxWidthRatio;box_height_ratio = param.boxHeightRatio;row_height = 1 ./ nRow;col_width = 1./ nColumn;xcPos = zeros(nColumn, 1);ycPos = zeros(nRow, 1);for iRow = 1:nRowfor iColumn = 1:nColumnrow_gap = (1 - box_height_ratio) * 0.5;col_gap = (1 - box_width_ratio) * 0.5;x = 0 + (col_gap + iColumn - 1) * col_width;y = 0 + (row_gap + iRow - 1) * row_height;w = col_width * (1 - col_gap);h = row_height * (1 - row_gap);xcenter = x + w/2;ycenter = y + h/2;xcPos(iColumn) = xcenter;ycPos(iRow) = ycenter;endendisHoldOn = ishold();if(~isHoldOn)cla();endhold('on');set(gca, 'XTick', xcPos, 'XTickLabel', param.AxisLabels);set(gca, 'YTick', ycPos, 'YTickLabel', param.AxisLabels);xlim([0 1]);ylim([0 1]);dim1 = get(gcf, 'Position');dim2 = get(gca, 'Position');axis_width = dim1(3) * dim2(3);axis_height = dim1(4) * dim2(4);width_to_height = axis_width / axis_height;alpha = 0.8;if(width_to_height >= 1)r_width_mult = 1 / (width_to_height^alpha);r_height_mult = 1;elser_width_mult = 1;r_height_mult = (width_to_height^alpha);endS = struct();S.FontSize = 10;[txt_width, txt_height] = measureText('-0.99', S, gca);scaling = max(txt_width / col_width, txt_height / row_height);desired_txt_gap = 0.9;font_size = max(floor(S.FontSize * (1/scaling) * desired_txt_gap), 1);if(isempty(param.FontSize))param.FontSize = font_size;endtxtOptions = struct();txtOptions.HorizontalAlignment = 'center';txtOptions.VerticalAlignment = 'middle';txtOptions.FontSize = param.FontSize;rec_line_width = param.BoxLineWidth;for iRow = 1:nRowfor iColumn = 1:nColumnrow_gap = (1 - box_height_ratio) * 0.5;col_gap = (1 - box_width_ratio) * 0.5;x = 0 + (col_gap + iColumn - 1) * col_width;y = 0 + (row_gap + iRow - 1) * row_height;w = col_width * (1 - col_gap);h = row_height * (1 - row_gap);xcenter = x + w/2;ycenter = y + h/2;xcPos(iColumn) = xcenter;ycPos(iRow) = ycenter;pos = [x y w h];color = param.Colors(iRow, iColumn, :);if(iRow > iColumn)rectangle('Position',pos, 'FaceColor', color, 'LineWidth', rec_line_width)txt = param.Labels{iRow, iColumn};text(xcenter, ycenter, txt, txtOptions);endif((iRow == iColumn) && param.ShowDiagonal)rectangle('Position',pos, 'FaceColor', color, 'LineWidth', rec_line_width)txt = param.Labels{iRow, iColumn};text(xcenter, ycenter, txt, txtOptions);endif(iRow < iColumn)cvalue = C(iRow, iColumn);theta_start = -0.5 * pi;theta_end = theta_start + (cvalue * 2 * pi);theta_range = theta_end - theta_start;n = 100;ww = w * param.RadiusRatio * r_width_mult;hh = h * param.RadiusRatio * r_height_mult;theta = [(0:n-1)]*(2*pi)/n;xx = xcenter + [0.5*ww*cos(theta)];yy = ycenter + [0.5*hh*sin(theta)];Pcircle = polyshape(xx,yy);theta = [(0:n-1) (n-1e-3)]*(theta_range)/n + theta_start;xx = xcenter + [0 0.5*ww*cos(theta)];yy = ycenter + [0 0.5*hh*sin(theta)];P = polyshape(xx,yy);plot(Pcircle, 'FaceAlpha', 0, 'LineStyle', '-', 'EdgeColor', [1 1 1] * 0.55);plot(P, 'FaceAlpha', 1, 'FaceColor', color);endendendset(gca, 'XDir', param.XDir);set(gca, 'YDir', param.YDir)if(~isHoldOn); hold('off'); endend
function [C] = color_spacing_continuous( values, breaks, colors)indices = zeros(size(values));for i = 1:length(breaks)if(i ~= length(breaks))q = values >= breaks(i);elseq = values > breaks(i);endindices(q) = indices(q) + 1;endratio = zeros(size(values));ranges = breaks(2:end) - breaks(1:(end)-1);for i = 1:(length(breaks)-1)ind = indices == i;ratio(ind) = (values(ind) - breaks(i)) / (ranges(i));endC = (1-ratio).*colors(indices, :) + ratio.*colors(indices+1, :);end
⛳️ 运行结果

本文介绍了如何在Matlab中利用corr函数生成相关矩阵,并通过heatmap函数创建热图以直观展示数据间的关系。通过色彩渐变,可以快速发现数据的相关性。此外,文章还提及了Matlab在其他领域的应用,如机器学习、图像处理、路径规划等。

被折叠的 条评论
为什么被折叠?



