-3

With R, how do I plot simple linear equations as lines on a plane? For example, how to plot line of the equation -2x + y = 0?

I did searched google but not got an answer.

Thanks!

Woody Wu
  • 358
  • 3
  • 13

1 Answers1

0

Although a duplicate here is a quick answer.

If one were to do this in excel, one would create 2 columns, 1 with x values and 1 with the corrosponding y values. For your situation the equation is equivalent to y = 2x. As such plotting can be by either calculating a range of values and plotting this as one would in excel.

Alternatively one can create a function and plot the function over an interval. Both methods are shown below.

#method one
x <- seq(from = 0, to = 10) 
y <- 2 * x
plot(y = y, x = x, xlab = "x", ylab = "y") #add type = 'l' for a line rather than a dot plot.

#method two
y <- function(x) 2 *x
plot(y, from = 0, to = 10)
Oliver
  • 8,169
  • 3
  • 15
  • 37
  • Thanks Oliver. The method one actually does not work. The method two is clear and cool. But I have two further questions. 1. I don't like the box, I want to have axes drawn as cross + just like in a normal math textbook. 2. I want to draw another line 2x + y = 2 (or y = -2x + 2) on the same picture. Can you kindly help? Thanks. – Woody Wu Jun 09 '19 at 12:55
  • Hello Woody, i simply forgot some quotation around the labels of the axis' `xlab = "x"` and `ylab = "y"` as these are just the x-axis label and y-axis label I hav eupdated the answer to show this.. In the case of multiple plots, the `lines`, `points` or similar which adds graphics to the current plot window. Use `help(lines)` to view the documentation for the function, with examples of how to use them. – Oliver Jun 09 '19 at 17:48