[SOLVED] How to fix ValueError for piecewise function plot

Issue

I am currently working on the following python script to plot the given piecewise function over the specified domain np.linspace(1.0, 3.0) and have run into some plotting errors. When I run the script, I am given the following error: ValueError: x and y must have same first dimension, but have shapes (50,) and (42,). I have tried adjusting the length of domain to match that of codomain by domain = np.linspace(1.0, 3.0, 42) but have had no luck. Here is my code given below:

import numpy as np
from matplotlib import pyplot as plt


def f(x):

    image = []
    for p in x:
        if p in np.linspace(1.0, 1.5):
            y = 1.000004 * (p - 1.0) + 0.486068 * (p - 1.0) ** 2 - 0.106566 * (p - 1.0) ** 3
            image.append(y)
        elif p in np.linspace(1.5, 2.0):
            y = 0.608198 + 1.406152 * (p - 1.5) + 0.326219 * (p - 1.5) ** 2 - 0.052277 * (p - 1.5) ** 3
            image.append(y)
        elif p in np.linspace(2.0, 2.5):
            y = 1.386294 + 1.693164 * (p - 2.0) + 0.247803 * (p - 2.0) ** 2 - 0.032798 * (p - 2.0) ** 3
            image.append(y)
        elif p in np.linspace(2.5, 3.0):
            y = 2.290727 + 1.916372 * (p - 2.5) + 0.198606 * (p - 2.5) ** 2 - 0.021819 * (p - 2.5) ** 3
            image.append(y)

    return image


domain = np.linspace(1.0, 3.0)
codomain = f(domain)

plt.plot(domain, codomain)
plt.show()

Disclaimer: this is my first post on this site so if there is anything I need to adjust for better feedback please let me know.

Solution

You seem to be misunderstanding what np.linspace is doing. Specifically, the values in np.linspace(1,1.5) are not guaranteed to be in np.linspace(1,3)

I would suggest reading the documentation to understand why this is.

You seem to want to split the original input into quartiles, which you could do with np.arraysplit(x,4)

import numpy as np
from matplotlib import pyplot as plt

def f(x):

    image = []
    a,b,c,d = np.array_split(x,4)
    for p in x:
        if p in a:
            y = 1.000004 * (p - 1.0) + 0.486068 * (p - 1.0) ** 2 - 0.106566 * (p - 1.0) ** 3
            image.append(y)
        elif p in b:
            y = 0.608198 + 1.406152 * (p - 1.5) + 0.326219 * (p - 1.5) ** 2 - 0.052277 * (p - 1.5) ** 3
            image.append(y)
        elif p in c:
            y = 1.386294 + 1.693164 * (p - 2.0) + 0.247803 * (p - 2.0) ** 2 - 0.032798 * (p - 2.0) ** 3
            image.append(y)
        elif p in d:
            y = 2.290727 + 1.916372 * (p - 2.5) + 0.198606 * (p - 2.5) ** 2 - 0.021819 * (p - 2.5) ** 3
            image.append(y)
        else:print(p)
    return image


domain = np.linspace(1.0, 3.0)
codomain = f(domain)

plt.plot(domain, codomain)
plt.show()

enter image description here

Answered By – Chris

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.