为什么 matplotlib 轮廓标签会使轮廓消失?

时间:2021-01-11 09:42:37

标签: python matplotlib contour

样本数据生成如下,

<ul>
    <li class="tree">
        <a href="#">Item</a>
        <ul class="sub-menu">
            <li><a href="#">Sub Item1</a></li>
            <li><a href="#">Sub Item1</a></li>
            <li><a href="#">Sub Item1</a></li>
        </ul>
    </li>
    <li class="tree">
        <a href="#">Item</a>
        <ul class="sub-menu">
            <li><a href="#">Sub Item2</a></li>
            <li><a href="#">Sub Item2</a></li>
            <li><a href="#">Sub Item2</a></li>
        </ul>
    </li>
</ul>

我尝试使用以下代码进行绘图,但调用 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

enter image description here

即使减小了轮廓线宽和标签字体大小,此问题仍然存在。

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

enter image description here

我不知道如何解决 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 的奇怪行为,我怀疑这是由于它们与对数刻度不兼容。

1 个答案:

答案 0 :(得分:3)

确实是对数轴的问题,尤其是在渐近线零附近。但是,为什么不在绘图前定义对数轴,以便 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()

示例输出: enter image description here