Clear Filters
Clear Filters

Statistic bar chart and lining the points of bar charts

8 views (last 30 days)
Hi Dears,
How can I have a line go through all the bar in the graph?
And how can I have the value of n_random label on each bar?
Please help me. I really appreciate that
close all;
clear all;
n = 50;
p = 0.2;
n_random = randi(15,1,n);
for i = 1:1:numel(n_random);
y= poisspdf(n_random(i),p);
figure (1);
yyaxis left;
hold on;
yb = cat(1, y.YData);
xb = bsxfun(@plus, h(1).XData, [h.XOffset]');
hold on;
padval = 1;
htxt = text(xb(:),yb(:)-padval, cellstr(num2str(yb(:))), ...
'rotation', 90, 'horiz', 'right');
set(htxt(1:3:end), 'color', 'w');
Dot indexing is not supported for variables of this type.
grid on;
sum1 = sum(y{i});
mean1 = mean(y{i});
fprintf('Mean of D is: %d',mean1);

Answers (1)

Shree Charan M L
Shree Charan M L on 21 Oct 2023
Hi Tu Nguyen,
I understand that you want to plot a line that goes through all the bars of the graph and display the value of “n_random” on top of each bar. However, the code you have provided is unclear with respect to what you’re trying to achieve with the xb” and “yb” variables. The variable “h” is not defined, and it may be useful to share the entire code snippet.
A line that goes through each bar can be plotted by using the “line” function. You can read more about the same here:
You can display the value of “n_random” on top of the bar using the “text” function. You can read more on the same here: You may also refer to this MATLAB Answers thread: for an example on the same.
Assuming, that you want to plot the Poisson probability density of n_random”, plot a line that goes through each bar and then label the top of each bar with the value of “n_random”, the following code snippet would do the trick:
close all;
n = 50;
p = 0.2;
n_random = randi(15, 1, n);
yyaxis left;
hold on;
y = poisspdf(n_random, p);
for i = 1:numel(n_random)
bar(i, y(i));
line(1:numel(n_random), y', 'Color', 'red', 'LineWidth', 2);
title('Poisson Distribution');
hold off;
grid on;
mean1 = mean(n_random);
fprintf('Mean of n_random is: %d\n', mean1);
Mean of n_random is: 8.420000e+00
Hope this helps.




Community Treasure Hunt

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

Start Hunting!