0
votes

I'm using Matlab and have created a histogram and want a vertical line to indicate the mean. So far my code is

N=100;
mydata=rand(N,1);
mymean=mean(mydata);
histogram(mydata);
figure(1)
hold on
line(mymean,N,'r')

I expect to find a red line crossing the x-axis at the mean value, but there is no line plotted. What is wrong here?

2

2 Answers

0
votes

I assume you want your line to go from the point p1=[mymean 0] to the point p2=[mymean N]. Just tell that to the line function. Right now you are drawing a line that only goes to a point, so it is that, a point.

line([mymean mymean],[0 N],'r')

But I see no reason to use line as it is just a low level function of plot, so just do

plot([mymean mymean],[0 N],'r')
0
votes

Starting in the 2018b version, xline() draws a vertical line.

N = 100;
mydata = rand(N,1);
mymean = mean(mydata);
h = histogram(mydata);
h2 = xline(mymean,'r-','LineWidth',1.5);    % Requires MATLAB R2018b or later

Other LineStyles are available: '-', '--', ':', '-.'.

h2.LineStyle = '--';  

Color is also easily changed.

For more info, see How to draw horizontal and vertical lines in MATLAB?, especially this answer.