Add a variable name to graphed points by selecting from a drop down menù
Afficher commentaires plus anciens
Hi to all,
I have a plot with some points and I need to assign a variable name to all these points. I would also like the variable name to be chosen from those available in a drop-down menu that opens when I click on the points themselves. Is it possible?
Réponses (1)
VINAYAK LUHA
le 11 Oct 2023
Hi Gianmarco,
I understand that you want to annotate data points in a "scatter" plot in MATLAB, with text chosen from dropdown menu options, which appears on clicking the datapoints.
Here is a solution to achieve the above use case using nested callback functions –
- Enable ‘data cursor’ mode using the “datacursormode” function, which allows interactive labelling of points by clicking on them.
- Create a callback function named “showDropDown” and assign it to the “UpdateFcn” property of the “datacursormode” object.
- Inside the “showDropDown” function, use the “uicontrol” function to create a dropdown menu.
- Pass a function called assignVariableName as the callback to assign the selected text (annotation) to the data points.
For your better understanding, I am attaching the code snippet that demonstrates this approach:
% Create a figure and plot your points
clc
clear all
close all
f = figure;
x = [1, 2, 3, 4, 5];
y = [2, 4, 1, 3, 5];
scatter(x, y);
hold on;
% Enable data cursor mode
dcm = datacursormode(f);
set(dcm, 'Enable', 'on');
% Create a callback function for the data cursor
dcm.UpdateFcn = @showDropdown;
% Callback function for the data cursor
function output_txt = showDropdown(~, event_obj)
% Get the clicked data point
xClicked = event_obj.Position(1);
yClicked = event_obj.Position(2);
% Create a drop-down menu
variableNames = {'A', 'B', 'C', 'D'};
dropdown = uicontrol('Style', 'popupmenu', 'String', variableNames, 'Position', [50, 40, 100, 20], 'Callback', @assignVariableName);
% Callback function for the drop-down menu
function assignVariableName(source, ~)
% Get the selected variable name from the drop-down menu
selectedVariable = variableNames{get(source, 'Value')};
% Display the variable name on the graph
text(xClicked, yClicked, selectedVariable, 'Color', 'red',FontSize=50);
% Delete the drop-down menu
delete(dropdown);
end
output_txt = "";
end
Further, you can refer to the following documentations of the functions used in the code snippet for more details:
- datacursormode: https://www.mathworks.com/help/matlab/ref/matlab.graphics.shape.internal.datacursormanager.html
- uicontrol: https://in.mathworks.com/help/matlab/ref/uicontrol.html
I hope you find the provided solution useful and this solution helps you label your data points according to your desired workflow.
Regards,
Vinayak Luha
Catégories
En savoir plus sur Interactive Control and Callbacks dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!