Get a look on the track topology on openrailwaymap:
https://www.openrailwaymap.org/?style=gauge&lat=62.774837258...
replies(4):
https://www.openrailwaymap.org/?style=gauge&lat=62.774837258...
Given that France invaded Spain in 1807, the military made it necessary to have a different gauge from France. Not only that, the train by the coast was also forbidden in some places as a naval bombardment could disrupt communications in case of war.
Spain has lots of mountains with a large plateau over 700 meters high and the coast is usually way lower so it makes sense to transport things by the coast.