Colormap by variable using plot function

46 次查看(过去 30 天)
Hello!
I am plotting data from a three-column table: x-value, y-value and cycleNumber. I would like to make a plot of y-value vs. x-value, but assign a different color from a colormap to each group of rows with the same cycle number.
I found how to do this using the scatter function:
s1 = scatter(table,'x-value','y-value','filled','ColorVariable','cycleNumber');
but I would prefer an output that the typical plot function gives. Is it possible to assign a 'ColorVariable' to the plot function?
Here is what my data look like right now. Not bad, but I wish the points were connected.
  3 个评论
nclsg
nclsg 2022-7-7
编辑:nclsg 2022-7-7
The only way I see would be to create new tables from the original table by filtering through the cycle number and then plot, e.g., 5 separate objects each with a colormap index.
The scatter function lets me plot this whole thing with one line of code. I've been looking for the equivalent of that 'ColorVariable' command within the plot function lit, but I can't find anything.
Rik
Rik 2022-7-7
That is indeed the way I would go. Remember that higher level functions provide easier tools, at the cost of flexibility.
But there may be another way: Mathworks engineers have probably done the exact same thing I'm suggesting you do. So they probably call plot (or the line primitive) somewhere in their code. This means you can query the Children properties of the axes (or the object returned by the scatter function) and you will probably eventually find line objects. When you do, you can edit the LineStyle properties to match what you need.
Not quite 1 line of code, but once you find the correct call, you should be left with 1 or 2 lines.

请先登录,再进行评论。

采纳的回答

Chunru
Chunru 2022-7-8
% generate data
x = rand(100,1);
c = randi([1, 5], [100, 1]);
y = exp(x).*c;
tbl = table(x, y, c);
scatter(tbl, 'x', 'y', 'ColorVariable', 'c');
cmap = jet(5); % 5 colors
figure; hold on
c1 = unique(tbl.c);
for i=1:length(c1)
idx = tbl.c == c1(i);
x1 = tbl.x(idx);
y1 = tbl.y(idx);
% sort x1
[x1, isort] = sort(x1);
y1 = y1(isort);
plot(x1, y1, 'Color', cmap(c1(i), :));
end
colormap(cmap)
colorbar
  1 个评论
nclsg
nclsg 2022-7-13
This worked!
(For my data, there was no need to sort x1). Thank you so much!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by