Williams was punished in the first set by the No. 24-seeded Muguruza, who looked by far the better player matching her in the heavy-hitting rallies and being more steady generally.
Muguruza won the first set in just 39 minutes and looked primed to cause the tournament's biggest upset since Roger Federer went out on Friday.
The American was struggling with her serve during the first set.
But Williams dug deep in set two with a more consistent and aggressive approach with her serve starting to work, to win it 6-3.
The second game of the decider proved crucial, when Williams saved five break points to hold for 1-1.
She broke the next game to lead 2-1, and then never looked back, serving out the match in just over two hours.
Williams will next play last year’s finalist, Dominika Cibulkova, who beat two-time champion Victoria Azarenka 6-2, 3-6, 6-3 in the fourth round.
"I decided to do my best and focus and stay relaxed," Williams said of another slow start.
"She hits the ball really big and really hard. I'm just really happy to be past the fourth round of a Slam," she added.