Joonie
Joonie

Reputation: 129

Equal spacing in bar graph in MATLAB

I have this bar graph in MATLAB, created using the bar command:

enter image description here

I was wondering if there is any way to get rid of empty spaces between 2478 and 2886, and between 4314 and 5130

If I can get the bars to have an equal amount of space in between them that would be perfect.

Upvotes: 6

Views: 1649

Answers (2)

Wolfie
Wolfie

Reputation: 30101

Your bars are drawn in the locations of your x data, and are spaced accordingly.

You could plot against [1, 2, 3, ..., 13] and re-label the axes like so

Example data:

x = [1886,2070,2274,2478,2886,3090,3294,3498,3702,3960,4110,4314,5130];
y = rand(1,13)*5 + 32;

Plotting

bar( 1:numel(y), y );
set( gca, 'XTickLabel', x );

plot

Upvotes: 6

hbaderts
hbaderts

Reputation: 14336

As described in the documentation of bar,

bar(x,y) draws the bars at the locations specified by x.

which means that this behavior is intended: Each bar is drawn at the exact position specified by x.

To get equally spaced bars, you can use the categorical function, which converts x to a data type which is intended for discrete categories. That way, you tell MATLAB that x is not a numerical vector where x(i) is the x-coordinate of the i-th element, but rather a simple label for that value.

bar(categorical(x), y)

Bar graph with categorical x-values

Upvotes: 11

Related Questions