As a tourist, I am thinking of visiting nearby city in Pyrenees, but the only way is to take the road so I might meet a lot of cars. Is it legal to walk on a road in Spain?
Yes it is, on public roads except where indicated with a sign like this:
Note though there was consideration given to make walking while drunk an offence: The Grauniad.
General advice for pedestrians is available at: Just Landed.
One one occasion I was staggering so much I risked falling over a cliff had I not aimed to follow the white line down the middle of the road. However I do NOT recommend that.
There are always hiking routes between cities. Specially in the Pyrenees. Ask in the tourist information point or ask the locals.
You can also look for military maps where hiking routes and walking paths are shown. Here you can see the official maps provided by the government of Spain: http://signa.ign.es/signa/