special data tip in matlab

5 views (last 30 days)
fima v
fima v on 17 Nov 2022
Answered: Abhinaya Kennedy on 26 Aug 2024
Hello i have a figure with multiple plots i want to make a data tip line as shown bellow.
so the points of intersectionof the red line with the plots will be the location of the data tips
and such data tip say what legent the red line crossed and the X,Y values of the intersection point?
is it possible ? because if we have 40 plots the 40 colors they all look the same . such "red line" could help see the legend of the plot so we want be confused
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 100*exp(-0.5*x).*sin(10*x);
figure;
hold on
plot(x,y1)
plot(x,y2)
hold off
legend('data1','data2')

Answers (1)

Abhinaya Kennedy
Abhinaya Kennedy on 26 Aug 2024
Yes, it’s possible to create data tips at the intersection points of the red line with the plots and display the legend and coordinates. Here’s how you can do it:
  1. Plot your data: You already have this part.
  2. Add the red line: Use the line function.
  3. Find intersection points: Use interpolation to find where the red line intersects the plots.
  4. Add data tips: Use the datatip function to add data tips at the intersection points.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 100*exp(-0.5*x).*sin(10*x);
figure;
hold on
p1 = plot(x, y1, 'DisplayName', 'data1');
p2 = plot(x, y2, 'DisplayName', 'data2');
legend('show');
% Add the red line
x_red = 10; % Example x-value for the red line
y_red = ylim;
red_line = line([x_red x_red], y_red, 'Color', 'red', 'LineWidth', 2);
% Find intersection points
y1_interp = interp1(x, y1, x_red);
y2_interp = interp1(x, y2, x_red);
% Add data tips
dt1 = datatip(p1, x_red, y1_interp);
dt1.Label = 'data1';
dt1.DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('X', x_red);
dt1.DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Y', y1_interp);
dt2 = datatip(p2, x_red, y2_interp);
dt2.Label = 'data2';
dt2.DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('X', x_red);
dt2.DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Y', y2_interp);
hold off
You can adjust the x_red value to place the red line at different x-values. This approach should help you distinguish between multiple plots even if their colors are similar.

Community Treasure Hunt

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

Start Hunting!