There might be a different way, this is what comes to mind:
label_offset_pixels = 15;
ax = gca;
old_units = get(ax, 'Units');
set(ax, 'Units', 'pixels');
ax_pos = get(ax, 'Position');
set(ax, 'Units', old_units);
label_x_pos_pixels = ax_pos(1) + ax_pos(3) + label_offset_pixels;
probe_text = text(label_x_pos_pixels, 1, 'test', 'Units', 'pixels');
set(probe_text, 'Units', 'data');
probe_pos_data = get(probe_text, 'Position');
label_x_pos_data = probe_pos_data(1);
delete(probe_text);
text(label_x_pos_data, y20, '20th pct');
text(label_x_pos_data, y80, '80th pct');
What this does is find the right boundary of the axes in pixels, add a margin, convert that to data units, and use the data units for the text position.
There is a considerably shorter way to find the normalized desired y coordinate, using the axes YLim properties, but that does not give you a fixed spacing between the box and the text. Though now that I think of it, you could do that, convert the result to Pixels, add the offset... yes, I guess that would be shorter in spirit
label_offset_pixels = 15;
ax = gca;
ax_ylim = get(ax, 'Ylim');
normalized_y20_80 = ([y20, y80]-ax_ylim(1))./(ax_ylim(2)-ax_ylim(1));
pct_text = text([1, 1], normalized_y20_80, {'20th pct', '80th pct'});
set(pct_text, 'Units', 'pixel');
pct_text_pos = get(pct_text, 'Position');
set(pct_text, {'Position'}, cellfun(@(xyz) xyz+[label_offset_pixels 0 0], pct_text_pos,'Uniform', 0));
set(pct_text, 'Units', 'data');
Best Answer