I'm trying to more or less replicate the following p-values density histogram, with different data:
So I want to create a histogram with the bin ticks at the beginning/end of a bar. With 15 bars and the values ranging from 0 up to and including 1.
At the moment I'm using the histc
command:
xint=1/15;
edges=(0:xint:1);
[n,bin]=histc(data,edges);
bar(edges,n,'histc');
tit='p-values histogram';
htitle=title(tit);
set(htitle,'fontname','Calibri')
xlabel('p-values');
ylabel('Frequency');
Which gives me:
However, if the data is equal to 1, the current code plots a new bar after 1. I guess I need to include the edges (to get the same as the example), but I couldn't seem to find the right command?
Also how can I make the histogram cut off at x=1, like the example? Inserting the "lambda arrow" of the example at 0.6 is preferable (but optional).
Edits 3 and 4: Since you're using Matlab R2013b, which doesn't have histogram
, use the number-of-bins syntax of hist
to plot:
[n, centers] = hist(data, 15)
Note that this returns centers, not edges of the bins. For the arrow, you can use annotation
if R2013b supports it. Alternatively (a bit hackish):
line([0.6 0.6], [1750 1250])
plot(0.6, 1250, 'Marker, 'v')
text(0.6, 1750, '\lambda', 'HorizontalAlignment','center', 'VerticalAlignment','bottom')
Edit 2: Try
xint=1/15;
edges_in=(0:xint:1);
histogram(data,edges_in);
to plot directly, rather than using bar
. This post from MathWorks says that the histc
option of bar()
is deprecated.
Use histcounts
instead of histc
:
xint=1/15;
edges_in=(0:xint:1);
[n,edges_out]=histcounts(data,edges_in); % <-- changed
size(n)
size(edges_in)
size(edges_out)
bar(edges_out(1:end-1),n,'histc'); % <-- changed - last bin edge shouldn't be included
tit='p-values histogram';
htitle=title(tit);
set(htitle,'fontname','Calibri')
xlabel('p-values');
ylabel('Frequency');
axis([0 1 0 2500]); % <-- added - but leave it off for debugging
Per the histc
docs, "The last bin consists of the scalar value equal to last value in binranges." So the last bin is just 1.0. By contrast, with histcounts
, "The last bin also includes the right bin edge, so that it contains X(i)
if edges(end-1) ≤ X(i) ≤ edges(end)
." That should do what you want.
I included an axis
above to tighten up the plot, but leave that off for debugging so you can see if the last bar is still there.
Edit Per the histcounts
docs, the returned vector has one fewer element than the edge vector. If that's the case (per the size
printouts in the edited code), it should be removed so bar
doesn't plot that bar.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments