'How can I add 45 degree line?

this is my ggplot code:

ggplot(data_fig, aes(x=money$diff_tr, y=av_change))+ geom_point()

and the output is:

output

but I want to add 45 degree line starting from the -15. Can you help me to add this line? Thank you.



Solution 1:[1]

No matter the scales for x or y, a 45 degrees line can be added like this.

p + geom_line(data = data.frame(x = c(-Inf, Inf), y = c(-Inf, Inf)), aes(x, y))

Solution 2:[2]

A 45 degree line will not stay at 45 degrees in ggplot unless you have a fixed aspect ratio in your plotting window. I think what you want is a line that goes from the bottom left at 15 to the top right of the plot.

I have had to approximate your data here from your plot to get an example to show you:

p <- ggplot(data_fig, aes(x=money$diff_tr, y=av_change)) + 
  geom_point()
  
p + geom_abline(slope = diff(layer_scales(p)$y$get_limits()) /
                  diff(layer_scales(p)$x$get_limits()),
                intercept = 0)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Merijn van Tilborg
Solution 2