Can a virus/spyware install itself on a system partition remotely? If I install malicious app accidentally can it copy itself onto the system partition? Or if a hacker gains access to my phone remotely can he install spyware onto the system partition?

I have read that malicious apps installed on system partition cannot be removed by factory reset or wiping the cache and the only way to remove them is by flashing the original firmware. Is this correct?

If possible then how can I prevent an unwanted software installing or being installed permanently?
Yes, under certain circumstances it is possible to install software remotely on your system partition. And yes, once a software is installed on the system partition it is immune to a factory reset, as the factory reset never changes the system partition.

However for doing so your device must be vulnerable to an exploit that allows to modify the system partition, as this is normally not possible from within a normal app.

Consider the two scenarios which are common ways to infect your device:


You install an app that contains malicious code that uses an exploit to temporary root your device and then installs itself onto the system partition.
You are surfing the web using a browser that has a vulnerability. You end up on a web site that exploits the vulnerability of your browser to download malicious code into browser. Afterwards the code additionally exploits your system similar to the first infection variant.


If you don't want to be affected by malicious code that installs itself permanently onto your device there are some basic guidelines:


Don't download apps from the internet or other untrusted app stores.
Or even better, don't install apps you don't know. 
Always install the updates for your favorite webbrowser app(s).
Use a device that regularity gets security updates from the vendor (the more often the better, for some devices there are security updates monthly). Hopefully this allows you to fix the security problems before an malicious app can use it.
Don't use a device that no longer receives security updates. If your device is no longer supported I would recommend to to root/unlock the device and install a recent version of LineageOS. Of course this usually means that you should consider this when buying a device (possibility of unlocking plus supported by LineageOS).