Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot y = mx + c with ggplot

Tags:

r

ggplot2

Basic question, ggplot doesn't seem to be doing what I expect though.

ggplot(data=data.frame( x=c(-1,2),y=c(-1,2) ), aes(x=x,y=y)) + 
  geom_blank() + 
  geom_abline(slope = -1 , intercept = 1)

I'm expecting this to plot :

enter image description here

It's plotting :

enter image description here

like image 452
baxx Avatar asked Nov 11 '18 13:11

baxx


2 Answers

The plot ggplot2 draws is not incorrect. It draws the function over the scales necessary to represent the data you pass to the aes call. It doesn't care whether you actually draw the data in a geom or not.

To illustrate the issue, it is helpful to add the actual data points to a plot and make the x- and y-axis more visible. The code below

ggplot(data=data.frame( x=c(-1,2),y=c(-1,2) ), aes(x=x,y=y)) + 
  geom_point(shape = 1) +
  geom_abline(intercept = 1, slope = -1, col = "red") +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0)

gives you: enter image description here

Since you only want to plot a subsection of the above plot, just correct the scales (and don't draw the axes and datapoints). Then you get the result you desire:

ggplot(data=data.frame(x=c(-1,2), y=c(-1,2)), aes(x=x,y=y)) + 
  geom_blank() +  # not necessary, taken from the OP's question
  geom_abline(intercept = 1, slope = -1) +
  scale_x_continuous(limits = c(0, 1)) +
  scale_y_continuous(limits = c(0, 1))

enter image description here

like image 147
apitsch Avatar answered Sep 22 '22 19:09

apitsch


I think ggplot2 does exactly what you ask it to do: you draw an empty canvans with goes from (-1, -1) to (2, 2) and then you add a abline. If you want to match the canvans to your exampe, just adjust the coordinates of the points that you specify:

library(tidyverse) 
ggplot(data=data.frame( x=c(0,2),y=c(1,0)), aes(x=x,y=y)) + 
    geom_blank() + 
    geom_abline(slope = -1 , intercept = 1)
like image 28
JReddig Avatar answered Sep 20 '22 19:09

JReddig