如何格式化Matplotlib的轮廓线

3 投票
1 回答
9317 浏览
提问于 2025-04-15 20:40

我正在使用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 个回答

3

这有点像是变通的方法,不过……

看起来在当前版本的Matplotlib中,等高线图不支持zorder(图层顺序)。不过,这个功能最近已经在主干代码中添加了

所以,正确的做法要么是等到1.0版本发布,要么就是直接从主干代码重新安装。

现在,接下来就是变通的部分了。我做了个简单的测试,如果我在

python/site-packages/matplotlib/contour.py

的第618行中,给collections.LineCollection的调用加上一个zorder,就能解决你遇到的具体问题。

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

这并不是正确的做法,但在紧急情况下可能会奏效。

另外,题外话,如果你接受一些对你之前问题的回答,你可能会在这里得到更快的帮助。大家都喜欢那些积分哦 :)

撰写回答