Home > Net >  How to make a contourf plot in python for a function defined by integral with calculating integral n
How to make a contourf plot in python for a function defined by integral with calculating integral n

Time:10-18

I need to make a contourf plot of a function that is too difficult to calculate analytically, so I calculated it with integrate.quad function in my code. Then I need a contourf plot, so I pass it to contourf plot function and it doesn't work.

I believe I don't understand the 2D and 1D arrays here.

Here is my idea of the code:

x=np.arange(0,5,0.1)
y=np.arange(0,5,0.1)
h=len(y)
v=[0,0]*h
[X,Y]=np.meshgrid(x,y)

for i in range(h):
  for j in range(h):
    f= lambda o:np.exp(o**6*x[i]*y[j])
    v[i,j], error= integrate.quad(f, 0, 2)

[X,Y]=np.meshgrid(x,y)
fig, ax=plt.subplots(1,1)
m=ax.contourf(X,Y,v)
ax.set_xlabel('x')
ax.set_ylabel('y')
cbar=fig.colorbar(m)
plt.show()

Could you please help me how to plot a function defined by integral and what is wrong with my approach?
Thank you

CodePudding user response:

The v array must have the same size as X (2D array):

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate

x=np.arange(0,5,0.1)
y=np.arange(0,5,0.1)
h = len(x)
[X,Y]=np.meshgrid(x,y)
v = np.zeros_like(X)
error = np.zeros_like(X)

for i in range(h):
    for j in range(h):
        f= lambda o:np.exp(o**6*x[i]*y[j])
        v[i, j], error[i, j] = integrate.quad(f, 0, 2)

fig, ax=plt.subplots(1,1)
m=ax.contourf(X,Y,v)
ax.set_xlabel('x')
ax.set_ylabel('y')
cbar=fig.colorbar(m)
plt.show()
  • Related