user314960
user314960

Reputation: 1

Python visualization of a function with 2 variables

I try to visualize a simple function with 2 variables. When the function is x**2 + y**2 the minima on the plot locates at (0, 0) as expected, but when the function is (x + 1)**2 + (y + 1)**2 the minima locates at (-1, 1). x coordinate is correct, but y coordinate is not (should be (-1, -1)). Could someone explain why when I add to x any value, x coordinate of the minima is always correct, but when I add any number to y, then y coordinate of the minima always locates in incorrect location? How can I fix it?

import numpy as np
import matplotlib.pyplot as plt

# Define the function
def circle(x, y):
    return (x + 1)**2+(y + 1)**2


# Grid for plotting
x = np.linspace(-3, 3, num = 101)
y = np.linspace(-3, 3, num = 101)
X, Y = np.meshgrid(x, y)


# 2D
plt.figure()
plt.imshow(circle(X, Y), extent = [-3, 3, -3, 3], cmap=plt.cm.jet)
plt.colorbar()

plt.show()

Plot

Upvotes: 0

Views: 1047

Answers (1)

Mr. T
Mr. T

Reputation: 12410

According to the matplotlib documentation you have to set origin to "lower":

import numpy as np
import matplotlib.pyplot as plt

# Define the function
def circle(x, y):
    return (x + 1) ** 2 + (y + 1) ** 2

# Grid for plotting
x = np.linspace(-3, 3, num = 101)
y = np.linspace(-3, 3, num = 101)
X, Y = np.meshgrid(x, y)

Z = circle(X, Y)

plt.imshow(Z, cmap = "jet", extent=[-3, 3, -3, 3],  origin = "lower")
plt.colorbar()
plt.show()

If origin is not specified, imshow defaults to the standard value, which is in this case the upper left corner. Hence only the y values are affected.

Alternatively, you could also use pcolor:

import numpy as np
import matplotlib.pyplot as plt

# Define the function
def circle(x, y):
    return (x + 1) ** 2 + (y + 1) ** 2

# Grid for plotting
x = np.linspace(-3, 3, num = 101)
y = np.linspace(-3, 3, num = 101)
X, Y = np.meshgrid(x, y)

Z = circle(X, Y)

plt.pcolor(X, Y, Z, cmap = "jet")
plt.axis([-3, 3, -3, 3])
plt.colorbar()

plt.show()

Upvotes: 1

Related Questions