How to display plot and rectangle at the same time?

I want to display some lines and some moving rectangles at the same time in the same frame. I use plot() to draw the lines, and rectangle() to draw the rectangles, but they can't display at the same time. And I have tried 'hold on' , but that didn't work, how can i solve the problem?
Any help would be appreciated!
Thanks

 Accepted Answer

" I have tried 'hold on' , but that didn't work"
My guess is that hold on was applied to the wrong axes. This can happen when the taget axis handle is not visible (ie, in App Designer). Specify the target axis handle using,
% ax is the axis handle
plot(ax, ___);
hold(ax,'on');
rectangle(ax, ___)
If this did not solve the problem please provide more detail in your question.

3 Comments

thank you so much!
Do I need to define 'ax'? and add ax as a variable to the functions?
Or there may be other ways that can combine these two figures together?
I use plot in the function 'drawlanes' and 'drawtraffic_lights'. My goal is to imitate a crossroad, finally I need to make all the cars(represented by rectangles) move, now I am just trying to draw rectangles. And here is my code so far.
w=input('Input the width of the road: ');
g=input('Input the time of the green light: ');
o=input('Input the time of the orange light: ');
r=input('Input the time of the red light: ');
drawlanes(w);
%a function draw the lanes
hold(ax,'on');
drawtraffic_lights(w,g,o,r);
%a function draw the traffic lights
%with 't' counting time
hold(ax,'on');
rectangle(ax,'Position',[0 0 1 3],'FaceColor','r');
Now I found that if I write the rectangle before, instead of after, the plot, then they can be displayed at the same time in the same frame, why could that happen? I think it's mysterious.
Anyway, thank you for answering my question!
"Do I need to define 'ax'?"
From my answer,
% ax is the axis handle
"Now I found that if I write the rectangle before, instead of after, the plot, then they can be displayed at the same time"
It looks like your rectangle was covering the other object. Nice job fixing that!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!