英文:
Matlab color-coded plot of matrix
问题
假设我有一个像这样的矩阵:
A = [0 -50 2;
0 -18 7;
0 13 3;
1 -50 3;
1 -18 5;
1 13 1;]
实际上,这个矩阵更大,但第一列是向上计数,而第二列是重复的。现在我想将其以颜色编码的方式绘制出来,得到类似于 此图 的结果,即 A(:,1) 和 A(:,2) 分别是 x 轴和 y 轴。
你会如何做呢?我尝试过 pcolor
、imagesc
等,但迄今为止都没有成功。如果这是一个重复的问题,我很抱歉 - 我已经搜索过 StackOverflow 和其他网站,但没有找到我可以使用的内容。
英文:
Say I have a matrix like
A= [0 -50 2;
0 -18 7;
0 13 3;
1 -50 3;
1 -18 5;
1 13 1;]
In reality, this matrix is larger but the first column is counting upwards while the second one is repetitive. Now I want to plot this colour-coded to get a result like e.g. this one, i.e. A(:,1) and A(:,2) are the x and y axes, respectively.
How would you do that? I've tried pcolor
, imagesc
and others but no luck so far. Sorry if this is a duplicate - I have searched stackoverflow and other websites but did not find anything that I could use.
答案1
得分: 2
以下是您要翻译的内容:
以下代码即使在由 x 和 y 列定义的网格具有 缺失 或 重复 条目的情况下也有效。在第一种情况下,结果将不包含缺失值的颜色(只有轴背景),而在第二种情况下,值将被覆盖。
该代码从数据生成一个矩阵,其中缺失的条目标记为 NaN
,然后使用 pcolor
显示它,该函数会忽略 NaN
条目。由于这个函数的工作方式,需要在显示之前向矩阵添加一列和一行。
A = [0 -50 2;
0 -18 7;
0 13 3;
1 -50 3;
1 -50 5;
1 13 1] % 示例。条目 (1,-50) 重复,条目 (1,-18) 缺失
[ux, ~, ind_x] = unique(A(:,1)); % x 的唯一值和它们的索引
[uy, ~, ind_y] = unique(A(:,2)); % y 的唯一值和它们的索引
B = NaN(numel(uy), numel(ux)); % 行是 y,列是 x
B(ind_y + size(B,1)*(ind_x-1)) = A(:,3); % 用线性索引将值填入 B
pcolor([B NaN(size(B,1),1); NaN(1,size(B,2)+1)]) % pcolor 丢弃最后一行和列
axis xy
xticks((1:numel(ux))+0.5), xticklabels(ux)
yticks((1:numel(uy))+0.5), yticklabels(uy)
colorbar
英文:
The following code works even if the grid defined by the x and y columns has missing or repeated entries. In the first case the result will contain no colour for the missing values (just the axis background), and in the second case the values will be overwritten.
The code generates a matrix from the data where the missing entries are marked with NaN
, and then displays it using pcolor
, which ignores NaN
entries. Because of how this function works, a column and a row need to be added to the matrix before displaying.
A = [0 -50 2;
0 -18 7;
0 13 3;
1 -50 3;
1 -50 5;
1 13 1] % example. Entry (1,-50) is repeated, and entry (1,-18) is missing
[ux, ~, ind_x] = unique(A(:,1)); % unique values of x and indices to them
[uy, ~, ind_y] = unique(A(:,2)); % same for y
B = NaN(numel(uy), numel(ux)); % row is y, column is x
B(ind_y + size(B,1)*(ind_x-1)) = A(:,3); % linear indexing to fill the values into B
pcolor([B NaN(size(B,1),1); NaN(1,size(B,2)+1)]) % pcolor discards last row and column
axis xy
xticks((1:numel(ux))+0.5), xticklabels(ux)
yticks((1:numel(uy))+0.5), yticklabels(uy)
colorbar
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论