Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a smooth 2D color plot for z = f(x, y)

I am trying to plot 2D field data using matplotlib. So basically I want something similar to this:

enter image description here

In my actual case I have data stored in a file on my harddrive. However for simplicity consider the function z = f(x, y). I want a smooth 2D plot where z is visualised using color. I managed the plotting with the following lines of code:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 21)
y = np.linspace(-1, 1, 21)
z = np.array([i*i+j*j for j in y for i in x])

X, Y = np.meshgrid(x, y)
Z = z.reshape(21, 21)

plt.pcolor(X, Y, Z)
plt.show()

However, the plot I obtain is very coarse. Is there a very simple way to smooth the plot? I know something similar is possible with surface plots, however, those are 3D. I could change the camera angle to obtain a 2D representation, but I am convinced there is an easier way. I also tried imshow but then I have to think in graphic coordinates where the origin is in the upper left corner.

Problem solved

I managed to solve my problem using:

plt.imshow(Z,origin='lower',interpolation='bilinear')

like image 224
Aeronaelius Avatar asked May 28 '15 14:05

Aeronaelius


People also ask

How do you smooth out a plot?

Select the plot in the Object Manager. In the Property Manager, select the Line tab. Check the Smooth line check box. Adjust the Smooth tension to obtain the desired smoothing.

How do I make matplotlib curve smooth?

Smooth Spline Curve with PyPlot:interpolate. make_interp_spline(). We use the given data points to estimate the coefficients for the spline curve, and then we use the coefficients to determine the y-values for very closely spaced x-values to make the curve appear smooth.


2 Answers

If you can't change your mesh granularity, then try to go with imshow, which will essentially plot any 2D matrix as an image, where the values of each matrix cell represent the color to make that pixel. Using your example values:

In [3]: x = y = np.linspace(-1, 1, 21)
In [4]: z = np.array([i*i+j*j for j in y for i in x])
In [5]: Z = z.reshape(21, 21)
In [7]: plt.imshow(Z, interpolation='bilinear')
Out[7]: <matplotlib.image.AxesImage at 0x7f4864277650>
In [8]: plt.show()

enter image description here

like image 197
wflynny Avatar answered Oct 20 '22 03:10

wflynny


you can use contourf

plt.contourf(X, Y, Z)

enter image description here

EDIT:

For more levels (smoother colour transitions), you can use more levels (contours)

For example:

plt.contourf(X, Y, Z, 100)

enter image description here

like image 21
tmdavison Avatar answered Oct 20 '22 05:10

tmdavison