I think it is mostly as a result of anxiety and nervousness. I have even noticed that I do it unconsciously once in a while, even when I was not in any way anxious or nervous. But when I look deeper into my life goals and expectations, I find out there are certain things that could have been troubling my life without getting adequate attention from me. Some other times, I think people shake their legs whenever they sit because sitting still is not a normal thing with them. Eventually, sitting still is an act you can still learn, no matter how long you have been shaking your legs while you are seated. If you fall into the category of people who cannot sit still for once, do whatever it takes to learn how to control the habit, because many people find it annoying.
I was always guilty of this habit severally. I was equally cautioned about this more than once, and advised against making it a habit by people who are very close to me. But I often thought it would be next to impossible for me to sit and not shake my legs, because to me, it would appear as if the whole world stood still and nothing would seem to be moving. It often felt quite strange and unnatural whenever I don't shake my legs while sitting, but with much efforts and focus, I learnt to stop, and I can now sit for long without moving a single leg. Occasionally, if I get nervous at work or have lots of work to get done, I can sometimes try shaking out my sillies a bit, though I catch myself most times before the leg shaking gets more serious. On the other hand, my boyfriend does it so very often, sometimes I get tempted to amputate him, lol.
I have suddenly found out that being the one on the receiving end is never a pleasant thing at all. Several times, I have tried to make him see reasons why he should work hard on beating the leg shaking habit, but he often says he can't imagine himself sitting and not shaking his legs, and therefore he has no plans to quit the habit. Sounds more or less like someone who is deep into drugs or other such feel-good stuff.
All the same, for every leg shaker reading this, please, make sure you put the people around you into consideration. This habit is one of the most irritating and annoying habits you can find out there today, especially when it makes the row of chairs, car or table shake in resonance with your legs. I don't see how shaking your legs makes you feel good at all or what makes it such an important ritual that always goes hand in hand with your sitting periods.