How to remove space between bars in bar graph for unequally spaced data?

7 views (last 30 days)
Hi, I am creating an app using MATLAB App Designer. This app asks the user for a specific year and uses interpolation to predict what the population might be in that year. I have taken the population data from 1901 to 2011. However when I try to plot the bar graph due to the unequally spaced data which relies on the user input, I am getting white space between the bars. This is my code uptill now:
cla(app.UIAxes);
year = app.EnterYearEditField.Value;
if (year>=1901 && year<=2001)
x = 1901:10:2001;
y = [238396327, 252093390, 251321213, 278977238, 318660580, 361088090, 439234771, 548159652, 683329097, 846427039, 1028737436];
estimated_population = interp1(x,y,year,'spline');
x = [x year];
y = [y estimated_population];
[x,sortIndex] = sort(x,'ascend');
y = y(sortIndex);
bar(app.UIAxes,x,y,'BarWidth',1);
end
Before clicking the plot button:
After clicking the plot button:
How do I remove this unwanted whitespace between the graphs that I get after clicking the plot command?
Thanks.

Answers (1)

the cyclist
the cyclist on 17 Apr 2021
To me, it seems like a bad idea to make the bars evenly spaced, if the data are not from evenly spaced years. If the x-axis represents time, surely the user expects each bar to be correctly placed in time. It is more important that a plot represents the data accurately, than be "pretty".
Instead, perhaps make the 1987 bar a different color, and be sure it is in front? I think that still looks good, and also faithfully represents the data.
  3 Comments
the cyclist
the cyclist on 18 Apr 2021
Edited: the cyclist on 18 Apr 2021
There are a couple different ways to manipulate the position of plot elements. Usually they will be "stacked" in the order they are plotted. But here is an example where I force the single red bar in front of the blue ones.
rng default
N = 7;
x0 = 1:N;
y0 = rand(N,1);
x_front = 3.9;
y_front = 0.5;
figure
hold on
h_f = bar(x_front,y_front,'r');
h_b = bar(x0,y0,'b');
uistack(h_f,'top')
legend([h_b,h_f],{'Data','Selected year'})
Also, I added a legend to distinguish the selected year, rather an x-axis label. (You could use num2str or sprintf to convert a numerical year to a string.)
Another option would be to use an annotation for the selected year instead, but it might be a bit tricky to do that dynamically with your data.
Aditya Rai
Aditya Rai on 18 Apr 2021
Thanks for your response! This way of stacking the graph on top seems to be a better method. I will surely try this. I appreciate you taking the time out to respond. Thanks again!

Sign in to comment.

Categories

Find more on Discrete Data Plots in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!