we can do such simulations making different assumptions about the mass of stars and gas in each galaxy, and so forth and see which matches the data best.
We find, by this method and others, that all galaxies are held together by the gravity not just of what we see.