How to add distance lines between bar graphs - matlab

I would like to indicate p-values between multiple bar graphs as in the figure below:
But I have not found relevant commands about this on MATLAB's page on bar graphs.
Here is my code for the bar graphs and the standard deviation graphics:
x = 1:3;
y = [17.5, 97.5, 100];
std = [23.84848004, 10.89724736, 0];
figure
hold on
bar(x,y)
errorbar(y,std,'.')
XTickLabel={'1' ; '2'; '3' ; '4'};
XTick=2:4:15
set(gca, 'XTick',XTick);
set(gca, 'XTickLabel', XTickLabel);

There is no such function that I know of, but it is easy to write one:
function [hl,ht] = overbar(x1, x2, y, txt)
sz = get(gca,'FontSize');
bg = get(gca,'Color');
d = 2; % size of hook, change depending on y axis scaling
hl = line([x1,x1,x2,x2], [y,y+d,y+d,y]);
ht = text((x1+x2)/2, y+d, txt, ...
'HorizontalAlignment','center', ...
'VerticalAlignment','middle', ...
'FontSize',sz, ...
'BackgroundColor',bg);
end
This function uses the axes' font size and color properties to determine how to draw the text. It first draws the line, then draws the text on top, using a solid background so that the line appears interrupted by the text.
This is how you would use it:
x = 1:3;
y = [17.5, 97.5, 100];
std = [23.84848004, 10.89724736, 0];
figure
hold on
set(gca, 'FontSize',16)
bar(x, y)
errorbar(y, std, '.')
set(gca, 'ylim',[0,150]);
XTickLabel = {'A', 'B', 'C'};
set(gca, 'xtick',x, 'XTickLabel',XTickLabel);
overbar(1 ,2, 120, 'p=0.037');
overbar(2, 3, 130, 'p<0.0001');
overbar(1, 3, 140, 'p<0.0001');

Related

Consulting waterfall chart matlab

I was trying to create "consulting" waterfall chart in matlab, and I am having a really difficult time in creating it. I was expecting actually that there would be a built in way of doing that.
Given this data:
x = [5, 2, -5, 8, 2, 12];
total = [1, 0, 0 ,0 ,0, 1];
I want to make a waterfall chart.
Basically, the vector x has the values for the chart and the vector total indicates whether the corresponding column is a total column or not.
So the first column, is a 5 and is a total column. The second column is a two and it is not (so it adds up). The third column is minus five so it subtracts, and so on and so forth until the last column which is a total again. Below how the figure would look like.
1) How to get this figure?
2) How to color increases, decreases and totals with different colors?
3) How to include the connecting lines?
Method 1
Here's one possible solution using MATLAB's bar function.
Assumptions:
The total columns are always the first and last columns.
The basic idea is to use the 'Baseline' property of a Bar object, which allows a particular bar to start from a specific value. For example, bar([1,3,5], 'BaseValue', 2) produces 3 bars that start from the value 2: the first going down by 1 unit, the second going up by 1 unit, and the last going up by 3 units.
From testing on R2019b, unfortunately it appears that all Bar objects on an Axes must share the same BaseValue. Thus, for each Bar object to have its own Baseline value, each of them must be on a separate Axes object. We can workaround this by overlaying a bunch of Axes (one for each Bar) on top of each other, making all but one of them transparent. This way all bars will be visible.
Anyways, here's the function. The inputs are
ax (optional): a handle to an existing Axes object. You may want to do this if you have other things plotted already, or if you want to manually set various properties of an Axes.
y: a vector of all the incremental values. Note: the final value is NOT required, i.e. to reproduce the plot in the question, use y=[5, 2, -5, 8, 2];
The function outputs the handles to each Bar object created. You may want this to further change the EdgeColor of the Bars.
function h = wfall(ax, y)
if nargin == 1
y = ax;
ax = gca;
end
if ~strcmp(ax.NextPlot, 'add')
fprintf('hold on not set for current axes. Overriding.\n');
hold(ax, 'on');
end
y = y(:); % column vector
n = length(y);
cumy = cumsum(y);
set(ax, 'XLim', [0, n+1]+0.5, 'YLim', [min(min(cumy), 0), max(max(cumy), 0)]);
% colors:
% decrease - red - code as -1
% total - black - code as 0
% increase - blue - code as 1
set(ax, 'CLim', [-1, 1], 'ColorMap', [1 0 0; 0 0 0; 0 0 1]);
% copy a bunch of axes
for i = 1:n
ax(i+1) = copyobj(ax(1), ax(1).Parent);
end
% Make all subsequent axes invisible
% Make sure all axes will always be the same size by linking properties
set(ax(2:end), 'Color', 'none', 'XColor', 'none', 'YColor', 'none');
linkprop(ax, {'XLim', 'YLim', 'Position', 'DataAspectRatio'});
% define from/to of each bar (except 1st and last)
from = cumy(1:n-1);
to = cumy(2:n);
% color of each bar (except 1st and last)
c = double(y>0) - double(y<0);
c(1) = [];
% first total bar
h = bar(ax(1), 1, from(1), 'CData', 0, 'BaseValue', 0);
% 2nd to 2nd last bars
for i = 1:n-1
h(end+1) = bar(ax(i+1), i+1, to(i), 'CData', c(i), 'BaseValue', from(i), 'ShowBaseLine', 'off');
end
% last total bar
h(end+1) = bar(ax(1), n+1, cumy(n), 'CData', 0);
% setting FaceColor flat makes the Bars use the CData property
set(h, 'FaceColor', 'flat')
Run the code as follows to produce the following plot.
close all;
ax = gca;
h = wfall(ax, y(1:end-1));
Method 2
Here's another solution if you prefer not to stack Axes objects on top of each other.
In this case, we make an additional assumption:
The cumulative value is never negative (this would apply, for example, the cash in my pocket)
Simply, each bar we draw can be considered as one colored bar (either blue/red) that is partially covered by a shorter white bar.
function h = wfall2(ax, y)
if nargin == 1
y = ax;
ax = gca;
end
if ~strcmp(ax.NextPlot, 'add')
fprintf('hold on not set for current axes. Overriding.\n');
hold(ax, 'on');
end
y = y(:); % column vector
n = length(y);
cumy = cumsum(y);
from = cumy(1:n-1);
to = cumy(2:n);
% color values:
% 1 - blue (increase)
% 0 - white
% -1 - red (decrease)
c = double(y>0) - double(y<0);
c(1) = [];
upper = max(cumy(1:n-1), cumy(2:n));
lower = min(cumy(1:n-1), cumy(2:n));
h(1) = bar(ax, 2:n, upper, 'FaceColor', 'flat', 'CData', c);
h(2) = bar(ax, 2:n, lower, 'FaceColor', 'w');
h(3) = bar(ax, 1, cumy(1), 'FaceColor', 'k');
h(4) = bar(ax, n+1, cumy(n), 'FaceColor', 'k');
set(h, 'EdgeColor', 'none')
set(ax, 'CLim', [-1, 1], 'ColorMap', [1 0 0; 0 0 0; 0 0 1]);
Run the function as follows:
close all;
ax = gca;
h = wfall2(ax, y(1:end-1));
The resulting plot:
The result, however, is a bit ugly by my personal standards, since the white bar will partially cover the x-axis. You can fix this, however, by setting the lower YLim to a negative value, i.e. set(ax, 'YLim', [-0.5 inf])

Shade and calculate specific area

I tried to change the code in a way so that only the first area is shaded grey. How can I set the horizontal line in a way that it only appears under the area I want to shade?
Furthermore I want to calculate the area of ONE region. How do I achieve that? I know it is trapz but I am not sure how to set the boundaries. Thanks!
x = 0:.01:4*pi; %// x data
y = sin(x); %// y data
level = 0.5; %// level
plot(x, y)
hold on
area(x, max(y, level), level, 'EdgeColor', 'none', 'FaceColor', [.7 .7 .7])
Curve:-
you can try also this simple option:
x = 0:.01:4*pi; %// x data
y = sin(x); %// y data
level = 0.5; %// level
lineStart = find(y>=level,1);
lineEnd = find(y(lineStart:end)<=level,1)+lineStart;
plot(x,y)
hold all
area(x(lineStart:lineEnd),y(lineStart:lineEnd),...
level,'EdgeColor', 'none', 'FaceColor', [.7 .7 .7],'ShowBaseLine','off')
line([x(lineStart),x(lineEnd)],[level level ])
hold off
without defining areas of interest a-priory:
And don't forget to hold off...
To calaulate the area:
A = trapz(x(lineStart:lineEnd),y(lineStart:lineEnd))
You can limit the range of your x axis in the area plot to the range of interest, e.g. from 0 to 4 and then calculate the resulting values of the function in this range. For the base line: you can hide it in the area command and add it manually using the line command.
x = 0:.01:4*pi; %// x data
y = sin(x); %// y data
level = 0.5; %// level
plot(x, y)
hold on
x_interest = 0:.01:4;
y_interest = sin(x_interest);
area(x_interest, max(y_interest, level), level, ...
'EdgeColor', 'none', 'FaceColor', [.7 .7 .7], ...
'ShowBaseLine', 'off');
line( [ min(x_interest) max(x_interest) ], [ level level ] )

How to create three Y-axis in one graph? [duplicate]

I have 4 sets of values: y1, y2, y3, y4 and one set x. The y values are of different ranges, and I need to plot them as separate curves with separate sets of values on the y-axis.
To put it simple, I need 3 y-axes with different values (scales) for plotting on the same figure.
Any help appreciated, or tips on where to look.
This is a great chance to introduce you to the File Exchange. Though the organization of late has suffered from some very unfortunately interface design choices, it is still a great resource for pre-packaged solutions to common problems. Though many here have given you the gory details of how to achieve this (#prm!), I had a similar need a few years ago and found that addaxis worked very well. (It was a File Exchange pick of the week at one point!) It has inspired later, probably better mods. Here is some example output:
(source: mathworks.com)
I just searched for "plotyy" at File Exchange.
Though understanding what's going on in important, sometimes you just need to get things done, not do them yourself. Matlab Central is great for that.
One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color' properties of the top two set to 'none' so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.
Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:
%# Some sample data:
x = 0:20;
N = numel(x);
y1 = rand(1,N);
y2 = 5.*rand(1,N)+5;
y3 = 50.*rand(1,N)-50;
%# Some initial computations:
axesPosition = [110 40 200 200]; %# Axes position, in pixels
yWidth = 30; %# y axes spacing, in pixels
xLimit = [min(x) max(x)]; %# Range of x values
xOffset = -yWidth*diff(xLimit)/axesPosition(3);
%# Create the figure and axes:
figure('Units','pixels','Position',[200 200 330 260]);
h1 = axes('Units','pixels','Position',axesPosition,...
'Color','w','XColor','k','YColor','r',...
'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
'Color','none','XColor','k','YColor','m',...
'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
'Color','none','XColor','k','YColor','b',...
'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
xlabel(h1,'time');
ylabel(h3,'values');
%# Plot the data:
plot(h1,x,y1,'r');
plot(h2,x,y2,'m');
plot(h3,x,y3,'b');
and here's the resulting figure:
I know of plotyy that allows you to have two y-axes, but no "plotyyy"!
Perhaps you can normalize the y values to have the same scale (min/max normalization, zscore standardization, etc..), then you can just easily plot them using normal plot, hold sequence.
Here's an example:
%# random data
x=1:20;
y = [randn(20,1)*1 + 0 , randn(20,1)*5 + 10 , randn(20,1)*0.3 + 50];
%# plotyy
plotyy(x,y(:,1), x,y(:,3))
%# orginial
figure
subplot(221), plot(x,y(:,1), x,y(:,2), x,y(:,3))
title('original'), legend({'y1' 'y2' 'y3'})
%# normalize: (y-min)/(max-min) ==> [0,1]
yy = bsxfun(#times, bsxfun(#minus,y,min(y)), 1./range(y));
subplot(222), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('minmax')
%# standarize: (y - mean) / std ==> N(0,1)
yy = zscore(y);
subplot(223), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('zscore')
%# softmax normalization with logistic sigmoid ==> [0,1]
yy = 1 ./ ( 1 + exp( -zscore(y) ) );
subplot(224), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('softmax')
Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.
Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!
close all
clear all
display('Generating data');
x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);
display('Plotting');
figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
'YColor','b',...
'YLim',[0,1],...
'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','left',...
'Color','none',...
'XColor','k',...
'YColor','r',...
'YLim',[0,10],...
'YTick',[1, 3, 5, 7, 9],...
'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)
ax3 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','g',...
'YLim',[0,100],...
'YTick',[0, 20, 40, 60, 80, 100],...
'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)
ax4 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','c',...
'YLim',[0,100],...
'YTick',[10, 30, 50, 70, 90],...
'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)
(source: pablorodriguez.info)
PLOTYY allows two different y-axes. Or you might look into LayerPlot from the File Exchange. I guess I should ask if you've considered using HOLD or just rescaling the data and using regular old plot?
OLD, not what the OP was looking for:
SUBPLOT allows you to break a figure window into multiple axes. Then if you want to have only one x-axis showing, or some other customization, you can manipulate each axis independently.
In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:
clear
clc
x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];
xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;
for i=1:N_
L=1-(numberOfExtraPlots*a)-0.2;
axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
if(i==1)
color = [rand(1),rand(1),rand(1)];
figure('Units','pixels','Position',[200 200 1200 600])
axes('Units','normalized','Position',axesPosition,...
'Color','w','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'NextPlot','add');
plot(x,Y(i,:),'Color',color);
xlabel('Time (s)');
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
else
color = [rand(1),rand(1),rand(1)];
axes('Units','normalized','Position',axesPosition,...
'Color','none','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
V = (xWidth*a*(i-1))/L;
b=xLimit+[V 0];
x_=linspace(b(1),b(2),10);
plot(x_,Y(i,:),'Color',color);
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
end
end
The code above will produce something like this:

matlab bar colormap returns the same color for all bars

I have a problem with using bar and colormap.
I have a csv file like this which contains completion time for six tasks:
34,22,103,22,171,26
24,20,41,28,78,28
37,19,60,23,141,24
...
and I create a bar chart with of the means, and add the std variation errorbar.
res = csvread('sorting_results.csv');
figure();
y = mean(res)';
e = std(res);
hold on;
bar(y);
errorbar(y,e,'.r');
title('Sorting completion time');
ylabel('Completion time (seconds)');
xlabel('Task No.');
hold off;
colormap(summer(size(y,2)));
Why is the output like this? Why do the bars have the same color? And how do I put legends to the six bars?
A piece of code that does the magic. It doesn't use the canonical technique mentioned by #am304, as you will have a hard time setting up the legend with it. Here, for each one of the 6 input values, we plot a full 6 bars: one bar with the value and the remaining five set to zero.
x = rand(1,6); %create data
x_diag = diag(x); %zero matrix with diagonal filled with x
cmap = summer(6); %define colors to use (summer colomap)
figure('color','w','Render','Zbuffer'); %create figure
%bar plot for each x value
for ind_data = 1:length(x)
h_bar = bar( x_diag(ind_data, :)); %bar plot
set( get(h_bar,'children'), 'FaceVertexCData', cmap(ind_data,:) ) ; %color
hold on;
end
colormap('summer');
%legend-type info
hleg = legend( ('a':'f')' );
set(hleg, 'box', 'off');
%xticks info
set(gca, 'XTickLabel', ('a':'f')' );
%plot errors
e = ones(1,6) * 0.05;
errorbar(x, e,'.r');
set(gca, 'FontSize', 14, 'YLim', [ 0 (max(x) + max(e) + 0.1) ]);
See Coloring 2-D Bars According to Height in the MATLAB documentation. Only the first colour of the colormap is used to colour the faces, you need a bit of hack (as per code on that doc page) to do what you want.

Combine the legends of shaded error and solid line mean

I am using this FEX entry to plot the horizontal shaded error bars for a variable plotted on the X-axis. This variable is plotted in different regions/zones and, therefore, there are 3 shaded error bars for 3 zones. I would like to combine the legends of the error bars (shaded region) as well as the mean (solid line) of any zone into a single legend represented by a solid line (or solid line inside a patch) of the same color as the zone.
THE WAY MY CODE WORKS FOR PLOTTING: A synthetic example of the way I am plotting is shown below
fh = figure();
axesh = axes('Parent', fh);
nZones = 4;
nPts = 10;
X = nan*ones(nPts, nZones);
Y = nan*ones(nPts, nZones);
XError = nan*ones(10, 4);
clr = {'r', 'b', 'g', 'm', 'y', 'c'};
for iZone = 1:nZones
X(:, iZone) = randi(10, nPts, 1);
Y(:, iZone) = randi(10, nPts, 1);
XError(:, iZone) = rand(nPts, 1);
% Append Legend Entries/Tags
if iZone == 1
TagAx = {['Zone # ', num2str(iZone)]};
else
TagAx = [TagAx, {['Zone # ', num2str(iZone)]}];
end
hold(axesh, 'on')
[hLine, hPatch] = boundedline(X(:, iZone), Y(:, iZone), XError(:, iZone),...
strcat('-', clr{iZone}), axesh, 'transparency', 0.15,...
'orientation', 'horiz');
legend(TagAx);
xlabel(axesh, 'X', 'Fontweight', 'Bold');
ylabel(axesh, 'Y', 'Fontweight', 'Bold');
title(axesh, 'Error bars in X', 'Fontweight', 'Bold');
end
THE WAY LEGENDS ARE SHOWING-UP CURRENTLY:
WHAT I HAVE TRIED:
As someone suggested in the comment section of that file's FEX page to add the following code after line 314 in boundedline code.
set(get(get(hp(iln),'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
However, on doing that I get this error:
The name 'Annotation' is not an accessible property for an instance of
class 'root'.
EDIT: The first two answers suggested accessing the legend handles of the patch and line which are returned as output the by the function boundedline. I tried that but the problem is still not solved as the legend entries are still not consistent with the zones.
There is a direct general way to control legends. You can simply choose not to display line entries by fetching their 'Annotation' property and setting the 'IconDisplayStyle' to 'off'.
Also, in order to use chadsgilbert's solution, you need to collect each single patch handle from every loop iteration. I refactored your code a bit, such that it would work with both solutions.
% Refactoring you example (can be fully vectorized)
figure
axesh = axes('next','add'); % equivalent to hold on
nZones = 4;
nPts = 10;
clr = {'r', 'b', 'g', 'm', 'y', 'c'};
X = randi(10, nPts, nZones);
Y = randi(10, nPts, nZones);
XError = rand(nPts, nZones);
% Preallocate handles
hl = zeros(nZones,1);
hp = zeros(nZones,1);
% LOOP
for ii = 1:nZones
[hl(ii), hp(ii)] = boundedline(X(:, ii), Y(:, ii), XError(:, ii),...
['-', clr{ii}], 'transparency', 0.15, 'orientation', 'horiz');
end
The simplest method as shown by chadsgilbert:
% Create legend entries as a nZones x 8 char array of the format 'Zone #01',...
TagAx = reshape(sprintf('Zone #%02d',1:nZones),8,nZones)'
legend(hp,TagAx)
... or for general more complex manipulations, set the legend display properties of the graphic objects:
% Do not display lines in the legend
hAnn = cell2mat(get(hl,'Annotation'));
hLegEn = cell2mat(get(hAnn,'LegendInformation'));
set(hLegEn,'IconDisplayStyle','off')
% Add legend
legend(TagAx);
There is not an easy way to do this, You have to go into the legend and shift things up:
The following makes a sample plot where the mean lines are not superimposed on the bound patches.
N = 10;
x = 1:N;
y = sin(x);
b = ones([N,2,1]);
[hl, hp] = boundedline(x, y, b);
lh = legend('hi','');
We get a structure g associated with the legend handle lh. If you look at the types of the children, you'll see that g2 is the mean line and g4 is the patch. So I got the vertices of the patch and used it to shift the mean line up.
g = get(lh);
g2 = get(g.Children(2));
g4 = get(g.Children(4));
v = g4.Vertices;
vx = unique(v(:,1));
vy = diff(unique(v(:,2)))/2;
vy = [vy vy] + min(v(:,2));
set(g.Children(2), 'XData', vx);
set(g.Children(2), 'YData', vy);
Not a simple answer, and definitely requires you do a crazy amount of formatting for a plot with more than one mean line/patch pair, especially since it will leave gaps in your legend where the last zone's mean line was.
As per your comment, if you just want the shaded error bars to mark the legend then it's pretty easy:
x = 0:0.1:10;
N = length(x);
y1 = sin(x);
y2 = cos(x);
y3 = cos(2*x);
b1 = ones([N,2,1]);
b2 = 0.5*ones([N,2,1]);
b3 = 0.1*ones([N,2,1]);
hold on
[hl, hp] = boundedline(x, y1, b1, 'r', x, y2, b2, 'b', x, y3, b3,'c')
lh = legend('one','two','three');
That's a nice FEX entry. You can associate a specific set of handles with a legend. And luckily, boundedline already returns the handles to the lines separately from the handles to the patches.
>> [hl,hp] = boundedline([1 2 3],[4 5 6], [1 2 1],'b',[1 2 3],-[4 5 6],[2 1 1],'r');
>> %legend(hl,{'blue line' 'red line'}); % If you want narrow lines in the legend
>> legend(hp,{'blue patch' 'red patch'}); % If you want patches in the legend.