对数刻度刻度线在 matplotlib python 中没有一致显示

问题描述 投票:0回答:1

我正在用符号学绘制 ax1 和 ax2,但是只有 ax2 显示逻辑刻度线,即使两者的生成代码是相同的。我尝试过使用

ax1.yaxis.set_major_locator(plt.LogLocator(base=10.0, numticks=15))
但它仍然没有达到预期的行为,我希望它是自动的。

def plot_optimization_results(history):
    """
    Plot the optimization results
    """
    iterations = [h['iteration'] for h in history]
    f_values = [h['f'] for h in history]
    F_norms = [h['grad_norm'] for h in history]
    x_values = np.array([h['x'] for h in history])
    
    # Create figure with subplots
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
    
    # Plot merit function value
    ax1.semilogy(iterations, f_values)
    ax1.xaxis.set_major_locator(plt.MultipleLocator(5))
    ax1.set_xlabel('Iteration')
    ax1.set_ylabel('Merit Function Value')
    ax1.set_title('Convergence of Merit Function')
    ax1.grid(True)
    
    # Plot norm of F(x)
    ax2.semilogy(iterations, F_norms)
    ax2.xaxis.set_major_locator(plt.MultipleLocator(5))
    ax2.set_xlabel('Iteration')
    ax2.set_ylabel('||F(x)||')
    ax2.set_title('Norm of F(x) vs Iteration')
    ax2.grid(True)

    ...
    return fig

enter image description here

python matplotlib
1个回答
0
投票

您可能已经注意到,与

ax1
相比,
ax2
中 y 值的范围要大得多,这就是为什么 (1) 并未显示所有主要刻度线(仅显示偶数指数的刻度线)和 (2 )小刻度线(您称为逻辑刻度线)被抑制。

根据这个相关问题的答案,我们可以

  • 通过将其 numticks 值(即允许的最大数量)设置为非常高的数字来强制显示所有
    major
    刻度线,
  • 再次通过将其 numticks 值设置为非常高的数字,并另外明确指定刻度间隔来强制显示所有
    minor
    刻度线。

这可能如下所示:

import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
vals = np.logspace(-13, 1)  # Some dummy data in the right range

ax1.semilogy(vals)  # Doesn't show all major ticks, doesn't show minor ticks
ax1.set_title("default")

ax2.semilogy(vals)
ax2.yaxis.get_major_locator().set_params(numticks=np.inf)  # Enforce all major ticks
ax2.set_title("all major ticks")

ax3.semilogy(vals)
ax3.yaxis.get_major_locator().set_params(numticks=np.inf)  # Enforce all major ticks
subs=np.linspace(.1, .9, num=9)
ax3.yaxis.get_minor_locator().set_params(numticks=np.inf, subs=subs)  # Set minor ticks
ax3.set_title("all major ticks + minor ticks")

这会产生: plot resulting from code above

我知道你说你希望这是自动的,但我不确定是否有更自动化的方式。为了提高自动化程度,您可以做的就是将所有必要的步骤包装到一个辅助函数中,然后您可以将其应用于所有绘图。

© www.soinside.com 2019 - 2024. All rights reserved.