【问题标题】:Plotting 3-tuple data points in a surface / contour plot using matplotlib使用 matplotlib 在曲面/等高线图中绘制 3 元组数据点
【发布时间】:2011-03-02 01:33:21
【问题描述】:

我有一些由外部程序生成的表面数据作为 XYZ 值。我想使用 matplotlib 创建以下图表:

  • 曲面图
  • 等高线图
  • 等高线图与曲面图重叠

我查看了几个在 matplotlib 中绘制曲面和轮廓的示例 - 但是,Z 值似乎是 X 和 Y 的函数,即 Y ~ f(X,Y)。

我假设我需要以某种方式转换我的 Y 变量,但我还没有看到任何示例来说明如何执行此操作。

所以,我的问题是:给定一组 (X,Y,Z) 点,我如何从该数据生成曲面图和等高线图?

顺便说一句,为了澄清,我不想创建散点图。此外,虽然我在标题中提到了 matplotlib,但我并不反对使用 rpy(2),如果这样可以让我创建这些图表。

【问题讨论】:

标签: python r matplotlib rpy2 surface


【解决方案1】:

使用 pandas 和 numpy 导入和操作数据,使用 matplot.pylot.contourf 绘制图像

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

【讨论】:

    【解决方案2】:

    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()
    

    rpy2 + lattice 的曲面图:

    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)
    

    【讨论】:

      【解决方案3】:

      为了制作等高线图,您需要将数据插入到常规网格http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data

      一个简单的例子:

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

      对于表面 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]])
      

      3D 轮廓 http://matplotlib.sourceforge.net/examples/mplot3d/contour3d_demo.html

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

      【讨论】:

      • sn-p 的 +1。这很有帮助。您能否解释一下您在表面 sn-p 中使用的变量(xim 和 yim)?我无法在任何地方看到它们的定义。
      • xim 和 yim 具有来自 xi 和 yi 的坐标矩阵。我编辑了答案以添加一些帮助片段(网格)
      • 如果数据已经在格子上,但只是格式化为三列 X、Y 和 Z 怎么办?有没有简单的 Python 方法将其转换为 imshow / 等高线图兼容格式?
      猜你喜欢
      • 2019-08-14
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2022-12-12
      • 1970-01-01
      • 2018-02-27
      相关资源
      最近更新 更多