【问题标题】:Matplotlib won't show minor ticks when using subplots使用子图时,Matplotlib 不会显示小刻度
【发布时间】:2019-11-01 14:32:19
【问题描述】:

我有几个子图,想通过 ax.tick_params 调整轴刻度设置。一切正常,但是没有显示 minor 刻度。这是一个代码示例

import matplotlib.pyplot as plt

x = np.linspace(0,1,100)
y = x*x

f, (ax1,ax2) = plt.subplots(2, 1)

ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)

ax1.plot(x,y)
ax2.plot(x,-y)

plt.show()

我认为 which=both 会给我小勾。但是我需要添加一个额外的

plt.minorticks_on()

这使得它们在 ax2 中可见但仅。

我该如何解决这个问题?

【问题讨论】:

    标签: python matplotlib plot subplot


    【解决方案1】:

    plt 将在当前轴上工作,在您的情况下为 ax2。一种方法是首先使用您所做的方式启用它们,然后使用 AutoMinorLocator 指定次要刻度的数量

    from matplotlib.ticker import AutoMinorLocator
    
    ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
    ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)
    
    ax1.plot(x,y)
    ax2.plot(x,-y)
    
    for ax in [ax1, ax2]:
        ax.xaxis.set_minor_locator(AutoMinorLocator(4))
        ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    

    【讨论】:

      【解决方案2】:

      使用 pyplot 的危险在于,您无法跟踪当前轴是 plt.minorticks_on() 之类的命令在哪个轴上运行的。因此,使用您正在使用的轴的相应方法将是有益的:

      ax1.minorticks_on()
      ax2.minorticks_on()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 2022-01-01
        • 2019-05-09
        相关资源
        最近更新 更多