How to Plot Numbers on top of Bar graphs?
396 次查看(过去 30 天)
显示 更早的评论
Assume we have this as data
Y=[198 138 172 188 190 192];
bar(Y);
How would I go about plotting the Y-values of each of the bars on top of the bars? So each bar would show its value on top of it.
0 个评论
采纳的回答
Chad Greene
2017-8-7
编辑:Chad Greene
2017-8-7
Y=[198 138 172 188 190 192];
bar(Y);
text(1:length(Y),Y,num2str(Y'),'vert','bottom','horiz','center');
box off
3 个评论
alankrita asthana
2017-11-16
hi @chad greene. i am trying to use the same command to display the Y values on top of my bar graph. it isnt working. kindly help
Chad Greene
2017-11-20
The phrase "it isn't working" does not contain enough information to help. I suggest reading this, then start another question with specifics about the issue you're having.
更多回答(5 个)
Johannes Stoerkle
2020-2-21
编辑:Johannes Stoerkle
2020-2-21
As an extension, I found a good approach if one wants to plot the number on the top of bars, which are displayed in several groups. Therefore, I estimate the correction for the text x-Position using an exp-function, which is fitted to my empirical results.
For instance. If you consider 3 categories and 7 different models (determined in first line) it results:
dataSample = reshape([36 2:21],3,7)';
figure
catStrArray = {'category1','category2','category3'};
catArray = categorical(catStrArray);
catArray = reordercats(catArray,catStrArray);
bar(catArray,dataSample')
nModel = size(dataSample,1);
nCat = size(dataSample,2);
xPosAmpl = 0.3682626-0.3298725*exp(-0.407004*(nModel-1)); % position amplitude
xPosInc = 2*xPosAmpl/(nModel-1);
modelNames = [];
for idxModel=1:nModel
bar_xPos = 1:nCat;
if nModel~=1
bar_xPos = bar_xPos-xPosAmpl+(idxModel-1)*xPosInc;
end
text(bar_xPos,dataSample(idxModel,:),num2str(dataSample(idxModel,:)',...
'%0.0f'),'vert','bottom','horiz','center');
modelNames{idxModel}=sprintf('model%d',idxModel);
end
legend(modelNames)
0 个评论
Benjamin Kraus
2024-11-1,0:34
Starting in MATLAB R2024b, Bar labels are now a built-in feature
Starting in MATLAB R2024b, Bar objects now have a Labels property that can be used to add labels to the tops of your bars. You can read about the new properties on the Bar objects property page.
For example:
Y=[198 138 172 188 190 192];
b = bar(Y, Labels=Y);
Solution for MATLAB R2019b through R2024a
If you can't upgrade to MATLAB R2024b just yet, you can use the XEndPoints and YEndPoints properties that were added in R2019b.
Y=[198 138 172 188 190 192];
b = bar(Y);
text(b.XEndPoints, b.YEndPoints, string(Y), ...
VerticalAlignment='bottom', HorizontalAlignment='center')
0 个评论
Edgar Mauricio Ocampo Alvarez
2022-4-23
编辑:Edgar Mauricio Ocampo Alvarez
2022-4-23
% this is the best solution:
xtips1 = bar(1).XEndPoints; ytips1 = bar(1).YEndPoints;
text(xtips1, ytips1, num2str(Y1,'%0.2f'),'HorizontalAlignment','left','VerticalAlignment','middle','Rotation',90,'FontSize',8);
xtips2 = bar(2).XEndPoints; ytips2 = bar(2).YEndPoints;
text(xtips2, ytips2, num2str(Y2,'%0.2f'),'HorizontalAlignment','left','VerticalAlignment','middle','Rotation',90,'FontSize',8);
0 个评论
Soyeun Jung
2017-8-7
Hi Ibro, you can run this line of code to display the y-values on top of each bar. See the attached link for related information. https://ch.mathworks.com/matlabcentral/answers/40629-bar-plot-value-on-top
text([1:length(Y)], Y', num2str(Y','%0.2f'),'HorizontalAlignment','center','VerticalAlignment','bottom')
0 个评论
Daniela Maria
2023-7-14
promedios = groupsummary(middle, 'Group', 'mean', {'IAAScore', 'MOScore'});
promedio_IAA = promedios.mean_IAAScore;
promedio_MO = promedios.mean_MOScore;
grupos = promedios.Group;
figure;
barras = bar(grupos, [promedio_IAA, promedio_MO]);
% Ajustar las etiquetas del eje x
xticklabels(grupos);
angle(45);
% Ajustar la orientación horizontal de las leyendas del eje x
ax = gca;
ax.XTickLabelRotation = 0;
% Cambiar el relleno de las barras a un gris más claro y el color del borde
color_relleno = [0.8, 0.8, 0.8]; % Gris claro
color_borde_IAA = 'red'; % Color del borde de IAAScore
color_borde_MO = '#4DBEEE'; % Color del borde de MOScore
ancho_borde = 1.5; % Ancho del borde de las barras
for i = 1:numel(barras)
barras(i).FaceColor = color_relleno;
if i == 1
barras(i).EdgeColor = color_borde_IAA;
else
barras(i).EdgeColor = color_borde_MO;
end
barras(i).LineWidth = ancho_borde;
promedios = groupsummary(middle, 'Group', 'mean', {'IAAScore', 'MOScore'});
promedio_IAA = promedios.mean_IAAScore;
promedio_MO = promedios.mean_MOScore;
grupos = promedios.Group;
figure;
barras = bar(grupos, [promedio_IAA, promedio_MO]);
% Ajustar las etiquetas del eje x
xticklabels(grupos);
xtickangle(45);
% Ajustar la orientación horizontal de las leyendas del eje x
ax = gca;
ax.XTickLabelRotation = 0;
% Cambiar el relleno de las barras a un gris más claro y el color del borde
color_relleno = [0.8, 0.8, 0.8]; % Gris claro
color_borde_IAA = 'red'; % Color del borde de IAAScore
color_borde_MO = '#4DBEEE'; % Color del borde de MOScore
ancho_borde = 1.5; % Ancho del borde de las barras
for i = 1:numel(barras)
barras(i).FaceColor = color_relleno;
if i == 1
barras(i).EdgeColor = color_borde_IAA;
else
barras(i).EdgeColor = color_borde_MO;
end
barras(i).LineWidth = ancho_borde;
end
% Añadir etiquetas y título
xlabel('Group');
ylabel('Stinging Frequency');
% Crear la leyenda sin recuadro
legend('IAA', 'MO', 'Box', 'off');
% Obtener el número de observaciones por valor único en la columna 'MOScore' y 'Group'
num_observaciones_MO = groupcounts(middle, {'Group', 'MOScore'});
% Obtener los valores únicos en la columna 'MOScore'
valores_MO = unique(middle.MOScore);
% Agregar el número de observaciones a las barras de MO
for i = 1:numel(barras)
if strcmp(grupos(i), 'MO')
% Obtener las coordenadas x y y de la barra actual
x = barras(i).XData + barras(i).XOffset;
y = barras(i).YData;
% Calcula la posición para colocar la etiqueta
x_pos = x;
y_pos = y + 0.05 * max(y); % Ajusta la posición vertical
% Obtener el número de observaciones para el valor de 'MOScore' correspondiente
num_observaciones = num_observaciones_MO(num_observaciones_MO.Group == grupos(i) & ismember(num_observaciones_MO.MOScore, valores_MO(i)), 3);
% Añadir la etiqueta a la barra actual en color negro y con un tamaño de fuente mayor
text(x_pos, y_pos, num2str(num_observaciones), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom', 'Color', 'k', 'FontSize', 10);
end
end
I'm trying with this codde, but the value doesn't appear and no error
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Directed Graphs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!