2010-06-10 7 views
19

J'ai des données de surface générées par un programme externe sous la forme de valeurs XYZ. Je veux créer les graphiques suivants, en utilisant matplotlib:Tracé de points de données à 3-uplets dans un tracé de surface/contour à l'aide de matplotlib

  • Superficie terrain
  • terrain Contour
  • terrain Contour recouvert d'une parcelle de surface

J'ai regardé plusieurs exemples pour tracer des surfaces et les contours dans matplotlib - cependant, les valeurs Z semblent être une fonction de X et Y, c'est-à-dire Y ~ f (X, Y).

Je suppose que je vais avoir besoin de transformer mes variables Y, mais je n'ai encore vu aucun exemple, qui montre comment faire cela. Donc, ma question est la suivante: étant donné un ensemble de points (X, Y, Z), comment puis-je générer des diagrammes de surface et de contour à partir de ces données? BTW, juste pour clarifier, je ne veux pas créer des nuages ​​de points. Même si j'ai mentionné matplotlib dans le titre, je ne suis pas opposé à l'utilisation de rpy (2), si cela me permet de créer ces graphiques.

+1

J'ai posté un exemple pour savoir comment mettre les données dans les tableaux 2-D pour pouvoir utiliser le tracé de la surface de matplotlib: http://stackoverflow.com/a/30539444/3585557. Jetez également un coup d'oeil à ces articles connexes/similaires/en double: 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 –

Répondre

23

pour faire un tracé de contour vous avez besoin interpoler vos données sur une grille régulière http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data

un exemple rapide:

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

pour la surface 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]]) 

contour 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 pour l'extrait. Cela aide beaucoup. Pourriez-vous s'il vous plaît expliquer les variables (xim et yim) que vous avez utilisées dans l'extrait de surface? Je ne peux pas les voir définis n'importe où. – morpheous

+0

xim et yim ont des matrices de coordonnées de xi et yi. J'ai édité la réponse pour ajouter quelques fragments d'aide (meshgrid) – remosu

+0

réponse génial! – ine

1

terrain Contour avec rpy2 + ggplot2:

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 terrain avec rpy2 + treillis:

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

Avec pandas géants et numpy à importer et manipuler des données, avec matplot. pylot.contourf pour tracer l'image

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

Questions connexes