How to have a discrete color bar for scatter3?

12 ビュー (過去 30 日間)
Fajri
Fajri 2016 年 3 月 23 日
回答済み: Makarand 2018 年 4 月 27 日
Hi all,
I have here residual errors as function of variable X and Y. The error ranges from 0 to (I think maximum) 3.7 something...
How can I have a discrete color for the marker and the color bar? Let's say that for error values from:
r < 0.5 --> color dark blue
0.5 < r < 1.0 --> color green
1.0 < r < 2.0 --> color yellow
2.0 < r --> color red
I have used scatter3 for the plot, the code looks like this:
scatter3(variable_X,variable_Y,residual_errors,[],residual_errors,'filled')
Thanks for your help!

採用された回答

Mike Garrity
Mike Garrity 2016 年 3 月 23 日
編集済み: Mike Garrity 2016 年 3 月 23 日
You want to use the colormap function to tell the axes what colors you want to use. That's pretty easy:
colormap([0 0 .5; 0 1 0; 1 1 0; 1 0 0])
But the problem is that MATLAB's colormap lookup is always linear. If your bins aren't all the same width, then it isn't that simple. You'll probably need something like this:
npts = 1e5;
x = randn(npts,1);
y = randn(npts,1);
z = randn(npts,1);
scatter3(x,y,z,32,z,'.')
crange = caxis;
t = linspace(crange(1),crange(2),64);
cmap = zeros(64,3);
mask = t<=.5;
cmap(mask,:) = repmat([.5 0 0],[sum(mask), 1]);
mask = t>.5 & t<=1;
cmap(mask,:) = repmat([0 1 0],[sum(mask), 1]);
mask = t>1 & t<=2
cmap(mask,:) = repmat([1 1 0],[sum(mask), 1]);
mask = t>2;
cmap(mask,:) = repmat([1 0 0],[sum(mask), 1]);
colormap(cmap);
You actually could simplify that a bit because the colormap will clamp to the last color for values that are off the end. That means that you could just have the linspace go between any two fixed values that are convenient. If you do that, you need to pass the values you use into the caxis function so the axes knows the range you're defining the colormap for.
  1 件のコメント
Fajri
Fajri 2016 年 3 月 24 日
Thank you Mike, I have tried your code and it works :)
I don't get the part with the simplification yet...do you mean I could let this part go?:
mask = t>2;
cmap(mask,:) = repmat([1 0 0],[sum(mask), 1]);
and the rest of error values greater than 2 would be automatically assigned a specific color?
Thanks again!

サインインしてコメントする。

その他の回答 (1 件)

Makarand
Makarand 2018 年 4 月 27 日
Try colorbar_levels

カテゴリ

Help Center および File ExchangeColormaps についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by