# Statistic bar chart and lining the points of bar charts

5 Ansichten (letzte 30 Tage)
Tu Nguyen am 25 Mär. 2022
Beantwortet: Shree Charan M L am 21 Okt. 2023
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?
clc;
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;
bar(i,y);
hold on;
yb = cat(1, y.YData);
xb = bsxfun(@plus, h(1).XData, [h.XOffset]');
hold on;
'rotation', 90, 'horiz', 'right');
set(htxt(1:3:end), 'color', 'w');
end
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);
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (1)

Shree Charan M L am 21 Okt. 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: https://www.mathworks.com/help/matlab/ref/line.html
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: https://www.mathworks.com/help/matlab/ref/text.html. You may also refer to this MATLAB Answers thread: https://www.mathworks.com/matlabcentral/answers/351875-how-to-plot-numbers-on-top-of-bar-graphs 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:
clc;
close all;
clear;
n = 50;
p = 0.2;
n_random = randi(15, 1, n);
figure(1);
yyaxis left;
hold on;
y = poisspdf(n_random, p);
for i = 1:numel(n_random)
bar(i, y(i));
end
line(1:numel(n_random), y', 'Color', 'red', 'LineWidth', 2);
text(1:numel(n_random),y',num2str(n_random'),'vert','bottom','horiz','center');
ylabel('Probability');
xlabel('Index');
title('Poisson Distribution');
xticks(1:numel(n_random));
xticklabels(cellstr(num2str(n_random')));
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.
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Bar Plots finden Sie in Help Center und File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by