MATLAB Answers

User selected points from a plot

40 views (last 30 days)
Kyle Wilkin
Kyle Wilkin on 14 Apr 2021
Commented: Kyle Wilkin on 14 Apr 2021
I need to visually inspect a certain metric and select the points that are good. I have something that works but it seems like there should be a better way to do this. My main issue is that the only functions I found selected a random spot on the axes and I would like to limit it to only selecting data points. I wrote a solution but it won't work with tightly spaced data points.
Is there a better way for a user to select points from a plot?
Code Below:
function [TotalImage,Points] = PickPeakImages(Struct);
%% Struct(1) is an NxNxi image array
% Struct(2) is time informations for each image
% Struct(5) is a measured value for each image
FN = fieldnames(Struct);
l = length(FN);
TotalImage = [];
Points = [];
f = figure;
title('Select Points then Press Enter')
for Si = 1:l
title('Select Points then Press Enter')
[x,~] = getpts(f); % I would like to select points from a plot and this is the closest I could find.
Points = cat(1,Points,x);
for xi = 1:length(x)
ImageIndex = (abs(Struct(2).(FN{Si}) - x(xi)) == min(abs(Struct(2).(FN{Si}) - x(xi)))); % Can't select a point from the plot itself so this gets the right index. It's ok for this purpose but really slow.
TotalImage = cat(3,TotalImage,Struct(1).(FN{Si})(:,:,ImageIndex));

Accepted Answer

Geoff Hayes
Geoff Hayes on 14 Apr 2021
Kyle - from, there is an answer that suggests using brush. Sample code that allow the user to pick (in this case 4) sets of data is as follows;
function [selectedXData, selectedYData] = DataPickerExample
close all;
% create some test data and plot it
x = -2*pi:0.1:2*pi;
y = sin(x);
hFig = figure;
hPlot = plot(x,y);
% create and enable the brush object
hBrush = brush(hFig);
hBrush.ActionPostCallback = @OnBrushActionPostCallback;
hBrush.Enable = 'on';
selectedXData = [];
selectedYData = [];
% select 4 sets of data points
for x=1:4
fprintf('select some points.\n');
% turn off the brush
hBrush.Enable = 'off';
function OnBrushActionPostCallback(~, ~)
xData = hPlot.XData;
yData = hPlot.YData;
brushedDataIndices = hPlot.BrushData;
selectedXData = [selectedXData xData(logical(brushedDataIndices))];
selectedYData = [selectedYData yData(logical(brushedDataIndices))];
  1 Comment
Kyle Wilkin
Kyle Wilkin on 14 Apr 2021
Thanks! With a bit of tweaking I think this will work well.

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!

Translated by