how to add data labels for bar graph in matlab

ⅰ亾dé卋堺 提交于 2019-12-11 03:24:52

问题


For example (code):

x = [3 6 2 9 5 1];
bar(x)

for this I need to add data labels on top of the each bar. I know that I have to use TEXT keyword, but I'm not getting how to implement it.


回答1:


Based off this answer:

data = [3 6 2 9 5 1];
figure; %// Create new figure
hbar = bar(data);    %// Create bar plot
%// Get the data for all the bars that were plotted
x = get(hbar,'XData');
y = get(hbar,'YData');
ygap = 0.1;  %// Specify vertical gap between the bar and label
ylimits = get(gca,'YLim');

%// The following two lines have minor tweaks from the original answer
set(gca,'YLim',[ylimits(1),ylimits(2)+0.2*max(y)]);
labels = cellstr(num2str(data'))                                   %//'

for i = 1:length(x) %// Loop over each bar
    xpos = x(i);        %// Set x position for the text label
    ypos = y(i) + ygap; %// Set y position, including gap
    htext = text(xpos,ypos,labels{i});          %// Add text label
    set(htext,'VerticalAlignment','bottom', 'HorizontalAlignment','center')
end



回答2:


After some attempts I have found the solution. Do the following:

y = Data;
for b = 1 : 10
    BarPlot(b) = bar(b, y(b), 'BarWidth', 0.9); % actual plot
    set(BarPlot(b), 'FaceColor', 'blue'); %Apply color
    barTopper = sprintf('%.1f%s', y(b)*100,'%'); % Place text on top
    text(b-0.5, y(b)+0.01, barTopper, 'FontSize', barFontSize); % position the text
    hold on;
end

Let me know if it works.




回答3:


Here is a simple solution with text:

x = [3 6 2 9 5 1];
bar(x)
ylim([0 max(x)*1.2])
text(1:numel(x),x+0.5,num2cell(x))



来源:https://stackoverflow.com/questions/31198739/how-to-add-data-labels-for-bar-graph-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!