Interactive Plot: click and display updated trace?
2 次查看(过去 30 天)
显示 更早的评论
Dear all,
I have a 3D matrix (in this example is "Data") and what I would like to do is:
- Plot the first slice
- Click on a specific point of the 2D-plot
- Get in another figure the behaviour of the point selected across the 3D matrix.
Now, the exapmple attached is doing exactly what I want.
However, is it possible to keep clicking on the figure and update the plot on the second figure without re-running the code every time?
Here the example:
clc
Size = rand(10,10,20);
Ax = linspace(1,10,10);
%
figure(1)
subplot 121
imagesc(Ax, Ax, Size(:, :, 1));
axis square xy
%
[xm, ym] = ginput(1); %xmouse, ymouse
[~, xidx] = min(abs(Ax-xm)); %closest index
[~, yidx] = min(abs(Ax-ym));
hold on
plot(Ax(xidx), Ax(yidx), 'rx')
%
trace = zeros(1, size(Size, 3));
for t2s = 1 : size(Size, 3)
trace(t2s) = Size(xidx, yidx, t2s);
end
subplot 122
plot(1:size(Size, 3), trace)
axis square xy
I saw that there might be some callback functions that can be used? I am using the ginput option..
Thanks for help!
Best,
E
0 个评论
采纳的回答
Zinea
2024-4-9
编辑:Zinea
2024-4-9
Hi Edoardo,
You can set up an interactive plot where clicking on the plot automatically updates another plot with the behaviour of that point across the 3D matrix, without having to rerun the code each time for a specific point.
This can be achieved using callback functions. Here is the code that has a function named “clickCallback” which is executed every time the 3D matrix is clicked on.
clc;
Size = rand(10,10,20);
Ax = linspace(1,10,10);
fig = figure(1);
subplot 121;
hImg = imagesc(Ax, Ax, Size(:,:,1));
axis square xy;
hold on;
hPoint = plot(NaN, NaN, 'rx');
% Create subplot for the trace plot
subplot(1,2,2);
hTrace = plot(NaN, NaN);
axis square xy;
xlim([1, size(Size, 3)]);
ylim([min(Size, [], 'all'), max(Size, [], 'all')]);
set(hImg, 'ButtonDownFcn', @(src, event)clickCallback(src, event, Ax, Size, hPoint, hTrace));
function clickCallback(~, ~, Ax, Size, hPoint, hTrace)
% Get the current point from the figure
pt = get(gca, 'CurrentPoint');
xm = pt(1,1);
ym = pt(1,2);
% Find the closest indices
[~, xidx] = min(abs(Ax-xm));
[~, yidx] = min(abs(Ax-ym)); %
% Update the point marker
set(hPoint, 'XData', Ax(xidx), 'YData', Ax(yidx));
% Extract and plot the trace
trace = squeeze(Size(xidx, yidx, :))';
set(hTrace, 'XData', 1:size(Size, 3), 'YData', trace);
end
Here is the link to the documentation to learn more about Creating and Executing Callback Functions : https://www.mathworks.com/help/imaq/creating-and-executing-callback-functions.html
Hope it helps!
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!