Devin
Devin

Reputation: 1086

How can I add labels (of values) to the top of my MATLAB plot?

I'm creating a histogram "manually" in MATLAB using the plot command on a dataset after using the hist command (where I can assign the output of the command to two matricies) to manually get the counts and midpoints. What I would really love to do is add a label above each of the bars on my histogram stating the centerpoint value of that column. Since I already have a vector containing all of those center values, my issue lies in figuring out how to actually create the labels and place them above each of the bars. Any help in adding these would be greatly appreciated!

What I've Tried So Far:

Based on another StackOverflow post, I saw a command along these lines

for b = 1:nBins
    text(bins(b),counts(b)*2,num2str(a(b==binIdx,1)),'VerticalAlignment','top')
end

I get the idea that I probably use the text command inside a loop to place a label above each bar, but when I attempted to modify the text command above to the data I had, I could not see the labels on my plot.

Upvotes: 2

Views: 21779

Answers (1)

Eitan T
Eitan T

Reputation: 32930

You can indeed use the example with text, but with a slight improvement.

text(x, y, ' a string') puts the text string in the location of point (x, y) on the graph. In your example, the x-coordiantes are OK (the centers of the bars) but each y-coordiante is at twice the height of the corresponding bar. This may get the text string placed outside the boundaries of the graph.

What I suggest you to do first is to set the y-axis in the following manner so that you have some extra room for the new text labels:

ylim([0, max(counts) * 1.2]);  %# The 1.2 factor is just an example

And then you use the example code from your question, like so:

A = fix(10 * rand(30, 1)) + 1; %# Randomize 30 samples between 1 and 10
[counts, bins] = hist(A);      %# Compute the histogram
figure, bar(bins, counts),     %# Plot the histogram bars
ylim([0, max(counts) * 1.2]);  %# Resize the y-axis

%# Add a text string above each bin
for i = 1:numel(bins)
    text(bins(i) - 0.2, counts(i) + 0.4, ['y = ', num2str(counts(i))], 'VerticalAlignment', 'top', 'FontSize', 8)
end

This is what you should get:

histogram

Here each label is placed 0.4 ticks above the corresponding bar y-axis), at a -0.2 tick offset from the center of the bar (x-axis).

Notice that I've also decreased the font size to 8 so that each label fits nicely with the width of each bar. You can, of course, play with the different properties of text to align your labels to your liking.

Upvotes: 10

Related Questions