For the most part, it’s tradition. While there are indeed general league rules about gym types (mostly to avoid having multiple gyms of the same type in the same league), most gym leaders choose their types or themes, based on preference, family obligations, or other personal factors.
The inclination to do so has a lot to do with how the original leagues were established. Back in the feudal days, warlords of Kanto and Johto represented themselves with an element and a crest. In order to settle minor conflicts, clans sometimes sent representatives to battle high-ranking officials of each other’s armies using pokémon of their clans’ respective types. This way, disputes can be settled with very little bloodshed. These battles became the foundation of gym matches, crests became badges, and once the League was established and feudalism fell, anyone can become a gym leader (although some leaders, like Falkner, are indeed descendants of those old warlords).
As for the Elite Four and champion … similar principle, but they often represent the emperor and the imperial guard, whose battles were more for recreation than conflict resolution.