필터 지우기
필터 지우기

Scatter use different colors for data-points

조회 수: 4 (최근 30일)
Cliff Karlsson
Cliff Karlsson 2018년 9월 16일
편집: dpb 2018년 9월 17일
I experimenting with the carbig dataset and want to use scatterplot3 to display some categories with different colors depending on how many cylinders the car got. How could I modify my code to work as expected? This is what I have tried:
load carbig
colors = [[1 0 0] [0 1 0] [0 0 1] [1 1 0] [1 0 1]];
c = [0 0 0]*length(Cylinders);
for i=1:length(Cylinders)
if Cylinders(i) == 8
c(i) = colors(5);
else
c(i) = colors(Cylinders(i)-2);
end
end
scatter3(Horsepower,Weight, MPG,[],c, 'Marker','.')
xlabel('Horsepower')
ylabel('Weight')
zlabel('Miles per Gallon')
title('Car Database')

채택된 답변

dpb
dpb 2018년 9월 16일
편집: dpb 2018년 9월 16일
Close, but... :) (Always a "but", isn't there or wouldn't be asking a Q?) VBG
colors = [[1 0 0] [0 1 0] [0 0 1] [1 1 0] [1 0 1]];
makes a 1x15 row vector instead of an array of 5 color triplets; you're missing the semicolon between the entries to keep them from just being strung together in one long row--
colors = [[1 0 0]; [0 1 0]; [0 0 1]; [1 1 0]; [1 0 1]];
Then, don't need the loop to assign them, use optional output from unique to locate the cylinder size in the array and use as lookup into the colors table:
[~,~,ib]=unique(Cylinders); % vector of each unique cylinder size index in Cylinders array
scatter3(Horsepower,Weight, MPG,[],colors(ib,:), 'Marker','.') % scatter using lookup into colors
  댓글 수: 4
Cliff Karlsson
Cliff Karlsson 2018년 9월 17일
Thanks but I still have a hard time understanding [~,~,ib]=unique(Cylinders); what does the ~ do?
dpb
dpb 2018년 9월 17일
편집: dpb 2018년 9월 17일
They just throw away the first two return values that we're not interested in for this application....but lets us get the third by being there for positional placeholders.
>> help punct
Punctuation.
. Decimal point. 325/100, 3.25 and .325e1 are all the same.
. Array operations. Element-by-element multiplicative operations
.
.
.
.
~ The tilde character can be used in function definitions to
represent an input argument that is unused within the function.
It can also be used to indicate that an output argument of a
function call is to be ignored. In this case, it must appear
within [ ] and be separated by commas from any other arguments.
Look at the documentation for unique to understand what the outputs are and why it's the third (and only the third) that we're interested in here.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by