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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1058115/image.jpeg)
3 个评论
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
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!