Understanding magnetoelectric switching in BiFeO$_3$ thin films