代码之家  ›  专栏  ›  技术社区  ›  Geddes

如何格式化matplotlib中的等高线

  •  3
  • Geddes  · 技术社区  · 14 年前

    我正在使用matplotlib生成隐式方程的图(例如y^x=x^y)。多亏了我已经得到的帮助,我已经走得很远了。我用等高线画出了这个图。我剩下的问题是如何设置等高线的格式,例如宽度、颜色,特别是zorder,其中等高线出现在我的网格线后面。当然,当绘制标准函数时,这些函数可以很好地工作。

    import matplotlib.pyplot as plt 
    from matplotlib.ticker import MultipleLocator, FormatStrFormatter
    import numpy as np 
    
    fig = plt.figure(1) 
    ax = fig.add_subplot(111) 
    
    # set up axis 
    ax.spines['left'].set_position('zero') 
    ax.spines['right'].set_color('none') 
    ax.spines['bottom'].set_position('zero') 
    ax.spines['top'].set_color('none') 
    ax.xaxis.set_ticks_position('bottom') 
    ax.yaxis.set_ticks_position('left') 
    
    # setup x and y ranges and precision
    x = np.arange(-0.5,5.5,0.01) 
    y = np.arange(-0.5,5.5,0.01)
    
    # draw a curve 
    line, = ax.plot(x, x**2,zorder=100,linewidth=3,color='red') 
    
    # draw a contour
    X,Y=np.meshgrid(x,y)
    F=X**Y
    G=Y**X
    ax.contour(X,Y,(F-G),[0],zorder=100,linewidth=3,color='green')
    
    #set bounds 
    ax.set_xbound(-1,7)
    ax.set_ybound(-1,7) 
    
    #add gridlines 
    ax.xaxis.set_minor_locator(MultipleLocator(0.2)) 
    ax.yaxis.set_minor_locator(MultipleLocator(0.2)) 
    ax.xaxis.grid(True,'minor',linestyle='-',color='0.8')
    ax.yaxis.grid(True,'minor',linestyle='-',color='0.8') 
    
    plt.show() 
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Mark    14 年前

    这有点老套但是…

    显然,在当前版本中,matplotlib不支持zorder的等高线。然而,这种支持, was recently added to the trunk .

    所以,正确的方法是等待1.0版本,或者直接从主干重新安装。

    现在,这里是黑客的部分。我做了个快速测试,如果我换了618号线

    python/site packages/matplotlib/contour.py

    要将zorder添加到collections.linecollection调用中,它将修复您的特定问题。

    col = collections.LineCollection(nlist,
       linewidths = width,
       linestyle = lstyle,
       alpha=self.alpha,zorder=100)
    

    不是正确的做事方式,但可能只是在紧要关头工作。

    另外,如果你接受了之前问题的一些回答,你可能会在这里得到更快的帮助。人们喜欢这些代表点:)