2010-06-10 27 views
19

Tengo algunos datos de superficie que un programa externo genera como valores XYZ. Quiero crear los gráficos siguientes, utilizando matplotlib:Trazado de puntos de datos de 3 tuplas en un gráfico de superficie/contorno usando matplotlib

  • parcela de superficie
  • Gráfico de contorno
  • parcela
  • Contour sobrepuesto con una parcela de superficie

He mirado en varios ejemplos para el trazado de las superficies y contornos en matplotlib - sin embargo, los valores Z parecen ser una función de X e Y, es decir, Y ~ f (X, Y).

Supongo que de alguna manera tendré que transformar mis variables Y, pero aún no he visto ningún ejemplo que muestre cómo hacerlo.

Entonces, mi pregunta es esta: dado un conjunto de (X, Y, Z) puntos, ¿cómo puedo generar gráficos de Superficie y contorno a partir de esos datos?

BTW, solo para aclarar, NO quiero crear diagramas de dispersión. Además, aunque mencioné matplotlib en el título, no soy reacio a usar rpy (2), si eso me permite crear estos gráficos.

+1

he publicado un ejemplo de cómo poner los datos en las matrices 2-D para poder utilizar la superficie de parcela matplotlib: http://stackoverflow.com/a/30539444/3585557. Además, eche un vistazo a estas publicaciones relacionadas/similares/duplicadas: http://stackoverflow.com/q/9170838/3585557, http://stackoverflow.com/q/12423601/3585557, http://stackoverflow.com/ q/21161884/3585557, http://stackoverflow.com/q/26074542/3585557, http://stackoverflow.com/q/28389606/3585557, http://stackoverflow.com/q/29547687/3585557 –

Respuesta

23

para hacer una parcela contorno necesita interpolar los datos en una cuadrícula regular http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data

un ejemplo rápido:

>>> xi = linspace(min(X), max(X)) 
>>> yi = linspace(min(Y), max(Y)) 
>>> zi = griddata(X, Y, Z, xi, yi) 
>>> contour(xi, yi, zi) 

de la superficie http://matplotlib.sourceforge.net/examples/mplot3d/surface3d_demo.html

>>> from mpl_toolkits.mplot3d import Axes3D 
>>> fig = figure() 
>>> ax = Axes3D(fig) 
>>> xim, yim = meshgrid(xi, yi) 
>>> ax.plot_surface(xim, yim, zi) 
>>> show() 

>>> help(meshgrid(x, y)) 
    Return coordinate matrices from two coordinate vectors. 
    [...] 
    Examples 
    -------- 
    >>> X, Y = np.meshgrid([1,2,3], [4,5,6,7]) 
    >>> X 
    array([[1, 2, 3], 
      [1, 2, 3], 
      [1, 2, 3], 
      [1, 2, 3]]) 
    >>> Y 
    array([[4, 4, 4], 
      [5, 5, 5], 
      [6, 6, 6], 
      [7, 7, 7]]) 

contorno en 3Dhttp://matplotlib.sourceforge.net/examples/mplot3d/contour3d_demo.html

>>> fig = figure() 
>>> ax = Axes3D(fig) 
>>> ax.contour(xi, yi, zi) # ax.contourf for filled contours 
>>> show() 
+0

+1 para el fragmento. Eso ayuda mucho. ¿Podría explicar las variables (xim e yim) que usó en el fragmento de superficie? No puedo verlos definidos en ningún lado. – morpheous

+0

xim y yim tienen matrices de coordenadas de xi y yi. Edité la respuesta para agregar algunos fragmentos de ayuda (meshgrid) – remosu

+0

¡respuesta increíble! – ine

1

Gráfico de contorno con rpy2 + ggplot2: parcela

from rpy2.robjects.lib.ggplot2 import ggplot, aes_string, geom_contour 
from rpy2.robjects.vectors import DataFrame 

# Assume that data are in a .csv file with three columns X,Y,and Z 
# read data from the file 
dataf = DataFrame.from_csv('mydata.csv') 

p = ggplot(dataf) + \ 
    geom_contour(aes_string(x = 'X', y = 'Y', z = 'Z')) 
p.plot() 

superficie con rpy2 + celosía:

from rpy2.robjects.packages import importr 
from rpy2.robjects.vectors import DataFrame 
from rpy2.robjects import Formula 

lattice = importr('lattice') 
rprint = robjects.globalenv.get("print") 

# Assume that data are in a .csv file with three columns X,Y,and Z 
# read data from the file 
dataf = DataFrame.from_csv('mydata.csv') 

p = lattice.wireframe(Formula('Z ~ X * Y'), shade = True, data = dataf) 
rprint(p) 
1

Con pandas y numpy para importar y manipular los datos, con matplot. pylot.contourf para trazar la imagen

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib.mlab import griddata 

PATH='/YOUR/CSV/FILE' 
df=pd.read_csv(PATH) 

#Get the original data 
x=df['COLUMNNE'] 
y=df['COLUMNTWO'] 
z=df['COLUMNTHREE'] 

#Through the unstructured data get the structured data by interpolation 
xi = np.linspace(x.min()-1, x.max()+1, 100) 
yi = np.linspace(y.min()-1, y.max()+1, 100) 
zi = griddata(x, y, z, xi, yi, interp='linear') 

#Plot the contour mapping and edit the parameter setting according to your data (http://matplotlib.org/api/pyplot_api.html?highlight=contourf#matplotlib.pyplot.contourf) 
CS = plt.contourf(xi, yi, zi, 5, levels=[0,50,100,1000],colors=['b','y','r'],vmax=abs(zi).max(), vmin=-abs(zi).max()) 
plt.colorbar() 

#Save the mapping and save the image 
plt.savefig('/PATH/OF/IMAGE.png') 
plt.show() 

Example Image

Cuestiones relacionadas