Reputation: 3407
Is there any elegant way of showing a two-dimensional PDF function?
I have a function F(x,y) and I want to illustrate it.
Here is one solution:
Generate a meshgrid and calculate the value of each point, then use imshow()
1 1.5 2 2.5 3 3.5
-----------------------
1| 0 0 0.1 0.2 0.3 0.5
1.5| 0 0.1 0.2 0.3 0.4 0.8
2| 0 0.1 0.2 0.3 0.5 0.8
2.5| 0 0.2 0.2 0.4 0.4 1
3| 0 0.1 0.2 0.3 0.5 0.8
However I don't know whether to use np.vstack or np.meshgrid to generate the "meshgrid".
Can anybody tell me how to draw the map above? Or provide a more "elegant" way to do it?
The solution below works perfect.
It yields the figure like this:
Upvotes: 4
Views: 1969
Reputation: 362756
You can use meshgrid
to make the coordinates:
import numpy as np
x = np.linspace(1, 3.5, 6)
y = np.linspace(1, 3, 5)
X, Y = np.meshgrid(x, y)
And then apply your F
at each point:
z = np.array([F(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = z.reshape(X.shape)
Now create a surface plot something like this:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('F(X, Y)')
plt.show()
You can of course use imshow
aswell, if you prefer to represent the F
using colour rather than using a 3D plot. It doesn't make much sense to use meshgrid if you're going to use imshow though.
Upvotes: 3