Background: Simple stimuli can evoke complex behavioral responses coordinated by multiple neural circuits. O-2 is an important environmental variable for most animals. The nematode C. elegans avoids high O-2, and O-2 levels regulate its foraging and aggregation. Results: Here, we dissect aggregation and responses to O-2 gradients into behavioral motifs and show how O-2 responses can promote aggregation. To remain in a group, C. elegans continually modify their movement. Animals whose heads emerge from a group will reverse or turn, thereby returning to the group. Re-entry inhibits further reversal, aiding retention in the group. If an animal's tail exits a group during a reversal, it switches to forward movement, returning to the group. Aggregating C. elegans locally deplete O-2. The rise in O-2 levels experienced by animals leaving a group induces both reversal and turning. Conversely, the fall in O-2 encountered when entering a clump suppresses reversal, turning, and high lo-comotory activity. The soluble guanylate cyclases GCY-35 and GCY-36, which are expressed in head and tail neurons, promote reversal and turning when O-2 rises. Avoidance of high O-2 is also promoted by the TRP-related channel subunits OCR-2 and OSM-9, and the transmembrane protein ODR-4, acting in the nociceptive neurons ASH and ADL. Both O-2 responsiveness and aggregation can be modified by starvation, but this is regulated by natural variation in the npr-1 neuropeptide receptor. Conclusions: Our work provides insights into how a complex behavior emerges from simpler behavioral motifs coordinated by a distributed circuit.