2

I am having trouble aligning the text above the correct bars in the following bar graph, I can't figure out where it's going wrong?

CODE:

bar(two_weeks,zAxis);
text(1:length(two_weeks),zAxis,num2str(zAxis),'vert','bottom','horiz','center');
box off
ylabel('Z Axis')

BAR CHART:

The arrows were added post production and are showing where they should be aligned to. Also note that I was too lazy to draw all of the arrows.

This is what is happening


DATA:

two_weeks = 
 1×14 datetime array
 [ 21-Nov-2018, 22-Nov-2018, 23-Nov-2018, 24-Nov-2018, 25-Nov-2018, 26-Nov-2018, 27-Nov-2018, ...
   28-Nov-2018, 29-Nov-2018, 30-Nov-2018, 01-Dec-2018, 02-Dec-2018, 03-Dec-2018, 04-Dec-2018 ]

zAxis = 
 [ 5, 12, 1, 7, 13, 24, 2, 27, 62, 0, 3, 17, 74, 4 ].'
Wolfie
  • 27,562
  • 7
  • 28
  • 55
SPYBUG96
  • 1,089
  • 5
  • 20
  • 38
  • 2
    Perhaps `text(0:length(two_weeks)-1, ...` fixes the alignment. – rinkert Dec 12 '18 at 21:03
  • @rinkert yeah that worked, I thought everything in MatLab was 1 indexed not 0 indexed. Why does that change for this instance? – SPYBUG96 Dec 12 '18 at 21:12
  • @SardarUsama My question isn't asking how to add labels of values on top of my matlab plot, I am already able to do that – SPYBUG96 Dec 12 '18 at 21:13
  • 2
    @SPYBUG96, that is indeed true, but in this case you are not indexing! You are specifying x values for the text. And apparently the first date corresponds to x location 0. – rinkert Dec 12 '18 at 21:15

1 Answers1

3

Your x axis is specified using a datetime array. What you're then using is guesswork to align indices (1:length(two_weeks)) for the x coordinates of your text items.

Instead, simply use the same datetime array for the position of the text!

bar( two_weeks, zAxis );
text( two_weeks, zAxis, arrayfun(@num2str,zAxis,'uni',0) );

As you did in the question, we want to set 'VerticalAlignment' to 'bottom' and 'HorizontalAlignment' to 'center' to neaten things up above the bars:

bar( two_weeks, zAxis );
text( two_weeks, zAxis, arrayfun(@num2str,zAxis,'uni',0), ...
      'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'center' );

Output:

bar plot

Wolfie
  • 27,562
  • 7
  • 28
  • 55