I use numpy.meshgrid method to draw a 3D plot in Python. the drawing is over variables d1, d2 but I have a function consist of array with 7 elements which is 3 elements are independent from d1, d2. When I try to draw my graph I face this error:
operands could not be broadcast together with shapes (7,) (120,120)
When I debug my code I see the array elements which are independent from d1, d2 has shape of 1 but the other ones have shape of 120. How I can draw such a function using numpy.meshgrid method ?
Thanks. The whole code is like as follows:
import numpy
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
def function(a, b, c, d1, d2):
Q = numpy.ones(7)
EV = []
EV.append(1 / (a + b))
EV.append(1 / (a + b + c))
EV.append(1 / (a + b + c))
EV.append((1 - numpy.exp(-c * d1)) / c)
EV.append((1 - numpy.exp(-c * d2)) / (c + a))
EV.append((1 - numpy.exp(-c * d1)) / c)
EV.append((1 - numpy.exp(-c * d2)) / (c + a))
return numpy.sum(numpy.multiply(Q, EV) / numpy.sum(numpy.multiply(Q, EV)))
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
d1 = numpy.arange(0, 6, 0.05)
d2 = numpy.arange(0, 6, 0.05)
X, Y = numpy.meshgrid(d1, d2)
# Plot the surface.
ax.set_zlim(2.00, 8.00)
surf = ax.plot_surface(X, Y, function(1, 1, 1, X, Y), cmap='viridis', linewidth=0, antialiased=False)
# Customize the z axis.
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
function(1, 1, 1, 0, 0)isarray([0.42857143, 0.28571429, 0.28571429, 0. , 0. , 0. , 0. ]). How would you want this to be plotted?np.meshgrid? the error occurs innumpy.sum(numpy.multiply(Q, EV) / numpy.sum(numpy.multiply(Q, EV))). not knowing what it is you want to calculate, anyhow, the result should be of shape (120,120) so you can call it inplot_surface(X, Y, Z)asZ.numpy.meshgridit produces a 2D array of all possible occurrence ford1, d2and pass it to the function. If you watch my function precisely you could see it produce 7 numbers which is 3 is independent ofd1, d2and the other ones hasd1, d2so the dimension of result is strange. The out is a list of 3 single number and 4 array of 120 x 120.