God allowed the ghost (spirit) of Samuel to appear to and converse with Saul when he went to the witch of Endor. If God has a purpose to allow the soul of a departed person to visit the earth, He could make it happen.
Some experienced exorcists (including Fr. Amorth, the chief exorcist of Rome) have observed in the course of their ministry that God allows some souls to visit the earth as ghosts, but some of these are demons masquerading as a departed soul. One way they can be differentiated, he says, by the activity of the entity. If the entity displays frightening or threatening behavior, it is likely a demon. Ghosts, on the other hand, are more benign and seem to be allowed to appear on earth to complete some unfinished business.
A relative of mine had an entity that kept appearing in her condominium last year (other condo owners there also reported strange things happening). She said it wasn't really scary, but it kept popping up and she got tired of it being around (this girl, BTW, is well educated and very level headed). She sent us the picture below and asked our advice on what she could do (you can see the two figures in the lower left-hand corner). I told her to get her parish priest to come and pray a blessing over the condo and if that didn't work to ask about getting an exorcism for the condo. She had a priest come by a couple of days later and did the blessing and, as far as I know, hasn't had any more visits.