If you plot the movement of mars across the Earth's sky it appears to move back on itself during its orbit.
Why does it appear to have a loop shape from Earth?
The effect is called apparent retrograde motion.
What happens is that Mars has a 'direction opposite to that of other bodies within its system as observed from a particular vantage point' when this loop occurs.
That's a bunch of words that don't mean a lot to me. A picture is worth a thousand clearer words:
(Imagine this turned sideways and you get the effect in your image)
Basically, because Earth and Mars are orbiting the sun at different rates, our vantage point of Mars changes for each combination of points in the orbit of each planet.
On this scale, the background of stars is pretty much stationary - any apparent movement of the stars due to this effect is going to be negligible. Thus, the stars are our point of reference.
As our vantage point of Mars changes, it appears to shift directions on the stellar background, creating the effect you describe.