Editing variable through graph

9 views (last 30 days)
MoHizzel
MoHizzel on 19 Jul 2017
Edited: Aashray on 21 Aug 2025 at 14:26
Hi there, Is there a way to edit a variable through its plot? Take the following code:
x = rand(5,1); plot(x,'*')
this will produce a plot with five points. Is it possible to click on any of the points, drag them on the plot to a new location, and have Matlab update the variable x accordingly?
Thank you!

Answers (1)

Aashray
Aashray on 21 Aug 2025 at 14:25
Edited: Aashray on 21 Aug 2025 at 14:26
I understand that you want to edit the contents of a variable x by dragging its plotted points so that the corresponding entries in x update automatically.
The issue with using a simple plot(x,'*') is that it only draws markers, which are not draggable by default.
The main change I made was to replace the static plot markers with drawpoint objects. Each data point is created as a draggable ROI, and I added listeners that trigger whenever a point is moved. Inside the callback, the x-coordinate is locked so that the index of the data point cannot change, only its y-value. The callback then updates the corresponding element of x and refreshes the line plot so that the results are immediately visible.
Here is my implementation for the same:
function drag_points
% Initial data
x = rand(5,1);
% Figure and axes
f = figure('Color','w');
ax = axes('Parent',f); hold(ax,'on'); box(ax,'on');
xlim(ax,[0.5 5.5]);
xlabel(ax,'Index'); ylabel(ax,'Value');
% Line plot for context
hLine = plot(ax, 1:numel(x), x, 'b-*', 'MarkerSize',8, 'LineWidth',1.2);
% Make draggable points
for k = 1:numel(x)
p = drawpoint(ax,'Position',[k x(k)],'Deletable',false);
addlistener(p,'MovingROI',@(src,evt) onMove(src,k));
addlistener(p,'ROIMoved', @(src,evt) onMove(src,k));
end
% Callback to update variable
function onMove(src,idx)
pos = src.Position;
pos(1) = idx; % lock to index
src.Position = pos;
x(idx) = pos(2); % update variable
hLine.YData = x; % refresh line
end
end
<I have attached a video depicting the desired funcitonality.>
You can refer the documentation links below for more details:

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!