0

I am trying to add the y=x line along with an offset from the y=x line a better way than the code I shared. For example, with Y=X, i want two additional diagonal lines +0.5 and -0.5 from the Y=X but the code I show is a bit harder to understand. Any help with this would be appreciated.

    x=np.linspace(0,5,101) 
    y=np.random.normal(x)    # add some noise

    plt.plot(x,y,'r.') # x vs y
    plt.plot(x,x,'k-') # identity line

    plt.plot(x+0.25,x-0.25,'b-') # identity line
    plt.plot(x-0.25,x+0.25,'b-') # identity line

    plt.xlim(0,5)
    plt.ylim(0,5)
    plt.show()

enter image description here

Charanjit Pabla
  • 373
  • 2
  • 5
  • 16

1 Answers1

0

It seems you wish to implement a function that plots linear lines for a given offset.

import numpy as np
import matplotlib.pyplot as plt


np.random.seed(123)
%matplotlib inline

# Functions
def linear(x, m=1, b=0):
    """Return y values for a line."""
    return x*m + b


def plot_offsets(x, func=linear, thres=0.25, ax=None):
    """Plot lines seperated by the given offset."""
    if ax is None:
        ax = plt.gca()
    half = thres/2.
    ax.plot(x+half, func(x, b=-half), "b-")        # lower
    ax.plot(x-half, func(x, b=half), "b-")         # upper
    return ax


# Data
x_lin = np.linspace(0, 5, 101) 
y_data = np.random.normal(x_lin)                   # add some noise


# Plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x_lin, y_data, "r.")                       # x vs y
ax.plot(x_lin, linear(x_lin), "k-")                # identity line
plot_offsets(x_lin, thres=0.5, ax=ax)
ax.set_xlim(0, 5)
ax.set_ylim(0, 5)
plt.show()

Two functions were added to your code to abstract plotting linear lines and linear "offsets" (given a threshold). Most of the remaining additions (np.random.seed, _, ax = plt.subplots) are included for reproducible code.

Output

enter image description here

pylang
  • 40,867
  • 14
  • 129
  • 121