Search code examples
pythonmatplotlibgraphingabsolute-value

I'm plotting absolute value functions in matplotlib and the graph just goes around the vertex


I'm trying to plot a function of f(X)= 2* abs(x-2)+4 but at the vertex or at point (2,4) the graph just stops and goes around it. Any way to change it so that it actually hits the point? thanks in advance.graph showing the problem

import matplotlib.pyplot as plt 
import numpy as np 
import math

def graph(width, hight):
  x = np.linspace(-width,width)


  fig = plt.figure()
  ax = fig.add_subplot(1, 1, 1)
  ax.spines['left'].set_position('center')
  ax.spines['bottom'].set_position('center')
  ax.spines['right'].set_color('none')
  ax.spines['top'].set_color('none')
  ax.set_ylim(-hight, hight)
  ax.set_xlim(-width, width)


  # the function
  y = 2 * abs(x-2)+4



  plt.plot(x,y,)


  plt.xticks(np.arange(-width, width+1, 1.0))
  plt.yticks(np.arange(-hight, hight+1, 1.0))
  plt.grid(True)
  plt.show()

graph(10, 10)

"""


Solution

  • The issue for your goal is your range that you create with linspace. The default number of samples is 50 for this method and they are evenly reparted so depending on your width, 2 might not be in this range. Use the num argument (third position) to increase this value and it will look better but your value might still not be in the range.

    (The problem is you're working on a list of numbers, you can't work on a infinite set).