Contour plot in python [duplicate] - python

This question already has answers here:
Make contour of scatter
(3 answers)
Closed 5 years ago.
I have 3 lots of data. These are x and y values as well as a temperature value for each xy point. I would like to plot each point and interpolate the area between points to get a continuous surface. The issue I have is specifying the temperature values. I can't get it to work with an equal number of x,y and z (temperature) values and all the examples I can find online use a function of x and y to create z or have z values for every point on an xy grid.
Is there a simple way to do this?
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots()
x = np.linspace(0, 1, 100)
y = np.linspace(0,1,100)
X, Y = np.meshgrid(x, y)
#Z = np.sin(X)*np.sin(Y) # want to specify not an equation
Z = np.linspace(1,2,100)
levels = np.linspace(-1, 1, 40)
cs = axs.contourf(X, Y, Z, levels=levels)
fig.colorbar(cs, ax=axs, format="%.2f")
plt.show()
Update:
Here is what I have so far. I still need to work out a good method to fill in the area between points. Does anyone have any ideas?
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots()
# create a grid in the correct shape / size
x = np.linspace(0, 1, 3)
y = np.linspace(0,1,3)
X, Y = np.meshgrid(x, y)
# specify and change the relevent areas
y = [1,2,0] # location of point in x direction
x =[2,1,1] #location of point in y direction
z = [40,30,20] #temperature
Z = np.arange(1,10).reshape((3,3))
Z[y,x] = z
levels = np.linspace(0, 40, 40)
cs = axs.contourf(X, Y, Z, levels=levels)
fig.colorbar(cs, ax=axs, format="%.2f")
plt.show()

The reason people use a function of x and y is because your Z value has to be a function of x and y. In your test code Z is 1D but it needs to be 2D to plot the contours.
If you have Z (temperature) values that have the same shape as your x and y coordinates then it should work.
x = np.linspace(0, 1, 100)
y = np.linspace(0,1,100)
X, Y = np.meshgrid(x, y)
#Z = np.sin(X)*np.sin(Y) # want to specify not an equation
Z = np.linspace(1,2,100)
print X.shape
print Z.shape
(100L,100L)
(100L)

Related

Contour plot of a multivariate function

I have a multivariate function
X is (2, 1), A(100, 2), and b is (100, 1).
How can I plot the contour plot of it in python? for a simple case like Z = X^2 + Y^2 I have this code, but I don't think it can work for my problem.
x, y = np.linspace(-3, 3, 400), np.linspace(-3, 3, 400)
XX, YY = np.meshgrid(x, y)
Z = (XX ** 2 + YY ** 2)
fig, ax = plt.subplots()
ax.contour(XX, YY, Z)
How can I plot contour of my function?
I assumed that in the pictured formula x is the same as X, which represents the coordinates of a point in a 2D plane.
Then, with np.meshgrid you create the usual grid of coordinates over which evaluating the function, xx and yy. At this points, you need to combine them into a matrix X of 2 rows (representing x and y coordinates) and as many columns as necessary.
Finally, you evaluate the function over each column of X.
import numpy as np
import matplotlib.pyplot as plt
# create example data
x = y = np.linspace(0, 2 * np.pi, 100)
A = np.stack([np.cos(x), np.sin(x * y)]).T
b = np.cbrt(x * y)
print("A.shape = ", A.shape)
print("b.shape = ", b.shape)
# define the function
f = lambda X: np.linalg.norm(b - A # X, 2)**2
# creates the coordinates over which the function
# will be evaluated
x = y = np.linspace(-np.pi, np.pi, 200)
xx, yy = np.meshgrid(x, y)
# assemble the coordinates into a "vector of coordinates"
X = np.stack([xx, yy]).reshape(2, -1)
print("X.shape = ", X.shape)
# apply the function f on each pair of coordinates
Z = np.apply_along_axis(f, 0, X).reshape(xx.shape)
print("Z.shape = ", Z.shape)
fig, ax = plt.subplots()
c = ax.contourf(xx, yy, Z)
fig.colorbar(c)
plt.show()

Plotting contours in python in Matplotlib

I am a beginner for data analysis or analytics,
My question here is, I have grid points (x and y) of a grid or a mesh and I have a corresponding temperature value for every grid point, I have to generate a 2D contour plot of temperature using that data which is present in an excel, Any idea on how to start on this topic, this would be of great help to me.
Here is an example of contour map from here
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y) # temperature
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar()
output :
matplotlib is good, but plotly is powerful and easier, you should try it.

How to plot a curve for a function in a 3D graphic - Python

I have this function:
z = 0.000855995633558468*x**2 + 0.0102702516120239*x + 0.00451027901725375*y**2 - 2.23785431578513*y + 251.029058292935
I also have lists (X, Y, Z) of the coordinates of the points from this function. Then I made this code to do a plot, of that coordinates:
fig = plt.figure()
ax = fig.gca(projection='3d')
plt.plot(X, Y, Z)
plt.show()
As you can see, with this code, I join the points by segments. How can I plot the curve that passes through those points?
In short, Python does not know how all xyz points need to be connected to each other to create a surface, so it just plots lines between them.
If you want to plot a surface whose z-coordinates are a function of its x and y coordinates you need to create a grid of all the possible combinations of xy coordinates and get the resulting z-grid. Then you can plot the grids.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def z_func(x, y):
z = 0.000855995633558468 * x ** 2 + 0.0102702516120239 * x + \
0.00451027901725375 * y ** 2 - 2.23785431578513 * y + \
251.029058292935
return z
# Creates a 1D array of all possible x and y coordinates
x_coords = np.linspace(-30, 30, 100)
y_coords = np.linspace(180, 220, 100)
# Creates 2D array with all possible combinations of x and y coordinates,
# so x_grid.shape = (100, 100) and y_grid.shape = (100, 100)
[x_grid, y_grid] = np.meshgrid(x_coords, y_coords)
# Evaluates z at all grid points
z_grid = z_func(x_grid, y_grid)
# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_grid,y_grid,z_grid)
plt.show()

Contour in Python

How Z is calcutalted in
from matplotlib.pyplot import contour
contour([X, Y,] Z, [levels], **kwargs)
to draw a contour?
I know that Z means: The height values over which the contour is drawn.
But is it drawn by calculating a standard deviation or something like that?
An average between each point I have?
Z represents a quantity dependent on both X and Y axes. If X and Y represent a plane, Z can be thought of as a surface, whose point height depends on the X and Y coordinates of that given point. The contour is a "top view" of that surface, a projection. An example are the contour lines which report the heights of the mountains (Z) as longitude (X) and latitude (Y) change.
The contour function of matplotlib, as you wrote it, plots the values expressed in the Z variable (two-dimensional numpy.ndarray, as X and Y) as they are, without further processing. The relationship between Z and X and Y is defined outside the plot function.
I report an example below which, perhaps it may be useful:
# IMPORT
import numpy as np
import matplotlib.pyplot as pl
# INPUT
N = 100
x_min = 0
x_max = 10
y_min = 0
y_max = 10
z_min = 0
z_max = 50
z_step = 1
red = '#de7677'
# DEFINE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)
# CALCULATE ZZ AS A FUNCTION OF XX AND YY, FOR ESAMPLE, THEIR SUM
ZZ = YY + XX
# PLOT THE CONTOUR
fig, ax = pl.subplots(figsize = (10, 10))
cont = ax.contour(XX,
YY,
ZZ,
levels = np.arange(z_min, z_max + z_step, z_step),
colors = red)
# SET THE CONTOUR LABELS
pl.clabel(cont, fmt = '%d')
# SET THE X AND Y LABEL
ax.set_xlabel('X')
ax.set_ylabel('Y')
pl.show()

Matplotlib contour hatching not working if only two levels was used

I am trying to plot hatches over contours lines that
statisfy certian criteria folliwng the example found here. Yet, I got regular contours (the yellow lines) instead of the hatches. Any ideas how to resolve that. Thanks
import matplotlib.pyplot as plt
import numpy as np
# invent some numbers, turning the x and y arrays into simple
# 2d arrays, which make combining them together easier.
x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)
# we no longer need x and y to be 2 dimensional, so flatten them.
x, y = x.flatten(), y.flatten()
fig2, ax2 = plt.subplots()
n_levels = 6
a=ax2.contourf(x, y, z, n_levels)
fig2.colorbar(a)
[m,n]=np.where(z > 0.5)
z1=np.zeros(z.shape)
z1[m,n]=99
cs = ax2.contour(x, y, z1,2,hatches=['','.'])
plt.show()enter code here
Use contourf() with proper parameters to get useful plot with hatching. See important comment within the working code below:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)
x, y = x.flatten(), y.flatten()
fig2, ax2 = plt.subplots()
n_levels = 6
a = ax2.contourf(x, y, z, n_levels)
fig2.colorbar(a)
[m,n] = np.where(z > 0.5)
z1=np.zeros(z.shape)
z1[m, n] = 99
# use contourf() with proper hatch pattern and alpha value
cs = ax2.contourf(x, y, z1 ,3 , hatches=['', '..'], alpha=0.25)
plt.show()
The output plot:

Categories