Matlab:如何在每个数据点获得不同颜色的散点图中设置图例颜色?

Matlab: How to set color of legend in a scatter plot where each data point gets a different color?

示例代码如下:

x = rand(100,1);
y = rand(100,1);
score = rand(100,1);
figure;
colormap(flipud(bone));
caxis([0 1])
axis([0 1 0 1])
scatter(x,y,50,score,'+','LineWidth',2);
legend('scores');

我正在使用反向 'bone' 颜色图,它将纯白色分配给分值 0,将纯黑色分配给分值 1。但是,图例似乎自动分配了分数 0,所以如果您运行代码图例颜色为纯白色,不可见。

有什么办法可以解决这个问题吗?谢谢

您要查找的是colorbar。这会显示一个颜色渐变条,用于所用颜色图中的所有值。

legend('scores'); 行替换为 colorbar

P.S。 legend 用于识别同一图中的多个图。

如果您只想绘制黑色 + 而不显示数据的颜色范围(与颜色条一样),您可以为此创建一个虚拟图例。以下是您的操作方法:

% plot some dummy data for the legend:
scatter(nan,nan,[],1,'+','LineWidth',2)
hold on
% plot your data:
scatter(x,y,50,score,'+','LineWidth',2);
hold off
% add the legend only for the first (dummy) data:
leg = legend('scores');

结果: