如何在 matplotlib 中以对数刻度和其他线性显示间隔

how to show an interval in logarithmic scale and other linear in matplotlib

我正在使用 matplotlib 并且我想绘制一个图表,其中 y 轴的负数部分具有较大的数字,而正数部分具有较小的值并且正数部分更有价值显示。所以我更喜欢以对数刻度绘制 y 轴的负部分,以线性(正常)刻度绘制正部分。在这里,我用对数刻度显示了整个图,这是我的代码:

    plt.plot(time_stamps,objs,'-rD', markevery=markers_on )
    markers_on=  list(i for i in range(len(upper_bound)))
    plt.plot(time_stamps,upper_bound,'-bD', markevery=markers_on )
    markers_on=  list(i for i in range(len(best_P_list)))
    plt.plot(exce_time_list,best_P_list,'-gD', markevery=markers_on)
    plt.xlabel("x", fontsize=10)
    plt.ylabel("y ", fontsize=10)
    plt.yscale('symlog')
    plt.show() 

如何以线性刻度显示 y 轴的正向部分?

我完全修改了我的答案,因为我发现 this SO answer 解释了如何划分轴以实现不同的行为。

现在,我们仍然需要将不同的值和步骤分开,但它更清晰。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np


vals = np.array([-1e10, -1e7, 1e3, 1e2, -1e8, -1e1, 1e3, 500])
steps = np.array([0, 5, 1, 4, 9, 20, 7, 15])


def plot_diff_scales(vals, steps):
    fig, ax = plt.subplots()
    ax.plot(steps[vals >= 0], vals[vals >= 0], "-gD")  # only positive values
    ax.set_yscale("linear")
    ax.spines["bottom"].set_visible(False)  # hide bottom of box
    ax.get_xaxis().set_visible(False)  # hide x-axis entirely
    ax.set_ylabel("Linear axis")
    # Dividing the axes
    divider = make_axes_locatable(ax)
    ax_log = divider.append_axes("bottom", size=2, pad=0, sharex=ax)
    # Acting on the log axis
    ax_log.set_yscale("symlog")
    ax_log.spines["top"].set_visible(False)  # hide top of box
    ax_log.plot(steps[vals < 0], vals[vals < 0], "-bD")  # only negative values
    ax_log.set_xlabel("X axis")
    ax_log.set_ylabel("Symlog axis")
    # Show delimiter
    ax.axhline(y=0, color="black", linestyle="dashed", linewidth=1)
    # Plotting proper
    fig.tight_layout()
    plt.show()


plot_diff_scales(vals, steps)