Graph plot multiple datasets: how to show dataset name when hovering over dataset
35 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ferry Nieuwland
am 11 Jun. 2023
Kommentiert: Ferry Nieuwland
am 12 Jun. 2023
Hello community,
Attached picture shows a plot generated by one of my scripts. The script plots multiple datasets. The legend is plotted on the chart.
I would like to see the legend name of the dataset when I hover over a dataset point. At this moment, as you can see in the screen dump, I get the (X,Y)-values. How can I get the legend name when hovering over data point? I would use this to identify and further investigate the outliers in the dataset.
Kind regards,
Ferry Nieuwland
0 Kommentare
Akzeptierte Antwort
Aman
am 12 Jun. 2023
Bearbeitet: Aman
am 12 Jun. 2023
Hi Ferry,
You can use the built-in Data Cursor tool in MATLAB to display custom information when hovering over data points on a plot.
Here's an example for the same,
% First, create a sample plot with multiple data series
figure;
x = linspace(0, 2*pi, 100);
y1 = sin(x);
plot(x, y1, 'r', 'DisplayName', 'sin(x)');
hold on
y2 = cos(x);
plot(x, y2, 'b', 'DisplayName', 'cos(x)');
hold off
legend('show')
% Next, create a data cursor object and update its properties
dcm = datacursormode(gcf);
set(dcm, 'UpdateFcn', @myupdatefcn)
% Define a custom update function that displays the legend name
function output_txt = myupdatefcn(~, event)
% Extract the data index and the x and y values
idx = event.DataIndex;
x = event.Position(1);
y = event.Position(2);
% Extract the legend name for the corresponding series
leg = event.Target.DisplayName;
% Create a cell array with custom display text
output_txt = {['Series:', leg], ['X:', num2str(x)], ['Y:', num2str(y)]};
end
Here, I have used sin and cosine plot for demonstration. This code first creates a sample plot with two data series and a legend. It then creates a Data Cursor object on the figure and defines a custom UpdateFcn function that will be executed whenever you hover over a data point on the plot.
The UpdateFcn function takes two arguments: the Data Cursor object and an event object containing information about the current data point. The function uses event.DataIndex to extract the index of the current data point, and event.Position(1) and event.Position(2) to extract the x and y values. It then uses event.Target.DisplayName to extract the legend name of the corresponding data series.
Finally, the function creates a cell array output_txt containing the custom display text, which is displayed when you hover over a data point on the plot.
Hope this helps!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!