With the score tied 2-2 in the sixth, Adrian Gonzalez doubled against Giants starter Mike Kickham (0-2) and Ramirez followed by driving a pitch down the left-field line that hit the foul pole for a two-run shot.
Matt Kemp, playing for the first time in 24 games, and Andre Ethier followed with consecutive singles, and Jake Dunning came in to pitch, only to surrender a run-scoring single to Tim Federowicz for a 5-2 Dodgers lead.
Ethier later came home with what turned out to be the decisive run when Dunning threw wildly to first on a pick-off attempt.
The Giants, trailing 6-3, mounted a comeback in the ninth against Los Angeles closer Brandon League, with Brandon Belt and Andres Torres each driving in a run before Paco Rodriguez took over on the mound.
With runners at first and second, he retired two batters before Kemp hauled in Marco Scutaro's long drive with an acrobatic catch at the wall to end the game and hand Rodriguez his first career save.
Stephen Fife (2-2) notched the win, allowing three runs on four hits over 6 2/3 innings as the Dodgers clinched the three-game series.