示例数据生成如下,
import matplotlib as mpl print(mpl.__version__) # 3.3.3 import matplotlib.pyplot as plt import numpy as np def f(x, y=0): return np.piecewise(x, [x < 1, np.logical_and(1 <= x, x < 10), x >= 10], [lambda x: 0, lambda x: (x - 1) / 9 * 1000, lambda x: 1000]) x = np.logspace(-5, 5, 100) y = np.logspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = f(X, Y)
我尝试使用以下代码进行绘图,但调用后一些轮廓消失了clabel。
clabel
fig, ax = plt.subplots(figsize=(5, 3), dpi=120) cr = ax.contour(X, Y, Z, levels=3, colors='black') ax.clabel(cr, inline=True, fontsize=8, fmt='%d') ax.set_xscale('log') ax.set_yscale('log') plt.show()
即使轮廓线宽和标签字体大小减小,此问题仍然会出现。
fig, ax = plt.subplots(figsize=(5, 3), dpi=120) cr = ax.contour(X, Y, Z, levels=3, colors='black', linewidths=0.6) ax.clabel(cr, inline=True, fontsize=3, fmt='%d') ax.set_xscale('log') ax.set_yscale('log') plt.show()
我不知道如何修复contour和的奇怪行为clabel,我怀疑这是由于它们与对数尺度不兼容造成的。
contour
这确实是对数轴的问题,尤其是在渐近线零点附近。但是,为什么不在绘图之前定义对数轴,以便 matplotlib 在绘图时可以考虑到这一点?
import matplotlib as mpl print(mpl.__version__) # 3.3.3 import matplotlib.pyplot as plt import numpy as np def f(x, y=0): return np.piecewise(x, [x < 1, np.logical_and(1 <= x, x < 10), x >= 10], [lambda x: 0, lambda x: (x - 1) / 9 * 1000, lambda x: 1000]) x = np.logspace(-5, 5, 100) y = np.logspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = f(X, Y) fig, ax = plt.subplots(figsize=(5, 3), dpi=120) ax.set_xscale('log') ax.set_yscale('log') cr = ax.contour(X, Y, Z, levels=3, colors='black') ax.clabel(cr, inline=True, fontsize=8, fmt='%d') plt.show()
示例输出: