Problem adding text to plot, background color doesn't work properly

I have encountered a problem using text to put labels inside a plot. I set the background colour to white. This works when I write the text over data plotted with plot, but it doesn't work over lines plotted with xline.
Here's my code:
figure;
plot( datimPingMBRY, timePingMBRY, 'r-' );
hold on;
plot( datimPingMVOFLS2, timePingMVOFLS2, 'b-' );
xline( logItemTime );
datetick( 'x', 'keeplimits' );
yLimits = ylim;
yText = yLimits(2) * 0.2;
t = text( logItemTime, yText*ones(nLogItems,1), string(logItemWhat), ...
'FontSize', 8, 'BackgroundColor', 'w', 'Rotation', 90 );
And here's the plot.
Any suggestions?

 Accepted Answer

The line does not through the label. However it is necessary to specify the label in the xline call —
xl = xline(0.5,'-','X-Line Label');
xl.LabelHorizontalAlignment = 'center';
xl.LabelVerticalAlignment = 'middle';
Also, it is likely more efficient to use datetime arrays than using datenum values (as would appear to be the situation from the datetick call). The xline function can use datetime and duration arguments to define its position.
.

5 Comments

Thanks.
Yes, datetime is much better, but I have several years' of using datenum and a lot of functions that need to be updated.
That didn't fully solve my problem as it doesn't have any effect on the data plotted with plot. But you've given me a good steer and I should be able to fix it from here.
As always, my pleasure!
I didn’t realise that you wanted the label background itself to be opaque with respect to the data. The ConstantLine Properties don’t include a way to make the line or its label area completely opaque. You would need something like patch for that.
x = linspace(0, 1, 500);
y = sin(2*pi*50*x);
figure
plot(x, y)
patch([0.38 0.62 0.62 0.38], [0.65 0.65 0.75 0.75], 'w', 'FaceAlpha',1, 'EdgeColor','none')
yline(0.7071,'-k','RMS Amplitude', 'LabelHorizontalAlignment','center','LabelVerticalAlignment','middle')
patch([0.49 0.52 0.52 0.49], [-0.16 -0.16 0.16 0.16], 'w', 'FaceAlpha',1, 'EdgeColor','none')
xline(0.5,'-k','Centre', 'LabelHorizontalAlignment','center','LabelVerticalAlignment','middle')
The patch argument vectors for the x-coordinates are [xlo xhi xhi xlo] and the y-coordinates [ylo ylo yhi yhi]. Of interest, these patch calls make the label areas opaque to the data, however not to other xline or yline plots (that appear to have special privileges in that regard).
Also, in the legend call, use 'Location','best' to put it where (most of the time) it will not overlap the data.
.

Sign in to comment.

More Answers (0)

Products

Release

R2022b

Tags

Community Treasure Hunt

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

Start Hunting!