Horizontal line in categorical bar plot?

23 views (last 30 days)
Viviane
Viviane on 5 Feb 2018
Answered: Fred Sallabank on 15 Dec 2018
Hello,
I'm trying to put a horizontal line in a bar plot. So far, this is what I've got:
As you can see, the line does not go from one end to the other of the graph. I guess it's because I have a categorical plot. Here's my code :
bar(Niveaux,Result.Moyennes(:,j), 'FaceColor',[0.847 0.835 0.835], 'EdgeColor',[0.847 0.835 0.835]); hold on;
ylim([0 40]);
xlim=get(gca,'xlim');
plot(xlim,[20 20], 'r', 'LineWidth',2); hold on;
plot(xlim,[29 29], 'k', 'LineWidth',2); hold on;
plot(xlim,[38 38], 'g', 'LineWidth',2);
Any idea?
Thank you for your help

Answers (1)

Fred Sallabank
Fred Sallabank on 15 Dec 2018
Yes, I think it is because you have a catergorial plot. When you put it in a string instead and specify the Xtick is seems to work.
%INPUTS
Data = [20;50;30];
Bounds = [25;55;35];
string = ["A","B","C"];
figure
bar(Data)
set(gca, 'XTickLabel',string, 'XTick',1:numel(string))
hold on
%Specify coordinates of lines
x = xlim;
y1 = [Bounds(1),Bounds(1)];
y2 = [Bounds(2),Bounds(2)];
y3 = [Bounds(3),Bounds(3)];
plot(x,y1,'b', x,y2,'g', x,y3,'r','LineWidth',2)
hold off
If you have to keep it catergorial I could only suggest altering the x cordinates of the lines manually, for instance:
xlim = get(gca,'xlim');
xlim = [xlim(1)-0.05, xlim(2)+0.05];

Products

Community Treasure Hunt

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

Start Hunting!