Los Blancos returned to the top of the table and once again lead Barcelona by three points after 34 games.
Cristiano Ronaldo scored in the 27th minute as he powered a headed effort home from Dani Carvajal's cross.
Karim Benzema almost doubled the lead after the half-time break but his effort came off the post, before the rebound fell for Luka Modric, who was brought down in the box.
Ronaldo then missed the resultant penalty, and Real were made to pay as Dani Parejo drew level with under 10 minutes to go.
However, Marcelo popped up outside the box to get onto the end of a cross from the right flank and skipped past his marker before firing a right-footed shot into the bottom-right corner.
The late win ensures the title race remains in Zinedine Zidane's side's hands with just four games remaining in the campaign.