简体   繁体   中英

How to add legend elements in Matlab in the plot itself

I want to somehow label vertical lines in Matlab. I could imagine two options: Either by having legend entries right next to each vertical line itself, or by having the vertical lines numbered in the graph and then having the numbers re-appear in the legend. Is either of this possible?

I do not want to use different colors or graph patterns because I have several vertical lines and the graph is otherwise hard to read.

x is a vector of date numbers and y is price data. Date1 and Date2 are dates that are element of x.

plot(x,y), grid on;
dateaxis('x',17);
line([Date1 Date1], ylim); % I would like to have a legend entry for this right at the line in the graph
line([Date2 Date2], ylim); % I would like to have a legend entry for this right at the line in the graph
legend('Price');

I think you probably want to use text objects instead of a legend. Here's an example (note that I had to use datetick instead of dateaxis because I don't have the Financial Toolbox ):

% Some sample data:
x = datenum(now():(now()+days(6)));
y = 1:7;

% Plot data:
plot(x, y);
grid on;
datetick('x');

% Make horizontal red lines:
line([x(1) x(1)], ylim, 'Color', 'r');
line([x(end) x(end)], ylim, 'Color', 'r');

% Add text:
text(x(1), mean(ylim), ' left');
text(x(end), mean(ylim), 'right ', 'HorizontalAlignment', 'right');

And the resulting plot:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM