Two points:
First, spacing is a bit more complicated than that, spacing also requires you to keep in account:
-Your and your opponent's movements, both vertically and horizontally.
-Timings for your movement's cooldown and your opponent's fastest options (upon whiffing, hitting a shield or a hit confirmation).
Proper spacing is very deep and is not easy, and you might lose a lot before learning how to do it, but in the long run is very rewarding.
Second, how to avoid getting grabbed depends on your character.
Pretty sure that you might still get grabbed even if you space well as Luigi.
You also need to know your own options and think about what will you do after you move. If after attacking you hold shield everytime you'll get grabbed. If you roll everytime you'll get punished. If you attack everytime you'll get punished too.
The "secret" to avoid getting grabbed is to mix up everything you do, and the timings in which you do it.
As a fun fact, at the beginning of a match I always grab a lot, that conditions my opponents not to hold shield and roll or attack instead; then I wait for them to act and punish them accordingly. When they cant up I start to grab a lot again. Pretty simple, and at the mid level we are at, pretty effective.