How to remove space between bars in bar graph for unequally spaced data?
9 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
the cyclist
2021-4-17
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 个评论
the cyclist
2021-4-18
编辑:the cyclist
2021-4-18
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Discrete Data Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!