How to program plots for linear equations (y=mx+b).

edited January 2018 in How To...

I've been searching a lot for this. I can't wrap my head about how to do it.

I need to graph it via y=mx + b. I'm quite new programming this kind of stuff.

Any guidance will be appreciated.

Thanks!

Tagged:

Answers

  • what's the range for x?

    because a for loop is a good way of iterating over all the values in a range...

  • that's the simplest thing; use a for loop with x

    then say y=7*x + 6; and then point(x,y);

  • edited January 2018 Answer ✓

    @dawnspectraa -- note that if it is a linear equation specifically, you don't actually need to loop over points and plot each point. You just need to solve for two points and then pass them to line().

    Solve x for the minimum and maximum y (or vice versa). Here is an example, which includes flipping the origin:

    void setup() {
      float m = random(0, 2); // slope
      float b = random(0, 50); // intercept
      float y1 = linear(m, 0, b);
      float y2 = linear(m, width, b);
      // origin is upper-left,
      // so subtract y values from height to flip upside-down
      // and make the origin bottom-left
      line(0, height-y1, width, height-y2);
    }
    
    float linear(float m, float x, float b) {
      return m*x + b;
    }
    

    If you want a nice graph (axis, labels etc.), without having to program it all yourself, try installing grafica.

  • There is also a method in grafica to draw these simple lines: plot.drawLine(slope, yCut)

    import grafica.*;
    
    void setup() {
      size(500, 350);
      background(150);
    
      // Define the line slope and cut
      float m = 1.0;
      float b = 0.1;
    
      // Create a new plot and set its position on the screen
      GPlot plot = new GPlot(this);
      plot.setPos(25, 25);
    
      // Set the plot title and the axis labels
      plot.setTitleText("Drawing a line: y = m*x + b");
      plot.getXAxis().setAxisLabelText("x axis");
      plot.getYAxis().setAxisLabelText("y axis");
    
      // Draw it!
      plot.beginDraw();
      plot.drawBackground();
      plot.drawBox();
      plot.drawXAxis();
      plot.drawYAxis();
      plot.drawTitle();
      plot.drawLine(m,b);
      plot.endDraw();
    }
    
Sign In or Register to comment.