【问题标题】:Matplotlib Secondary x-Axis with different Labels & Ticks具有不同标签和刻度的 Matplotlib 辅助 x 轴
【发布时间】:2020-06-25 11:33:55
【问题描述】:

我想用两个 x 轴绘制一些东西。但是 xticks 不对齐。不知何故,边距被忽略了?!在最终版本中,xlabels 是不同的,这意味着仅在顶部显示轴不是一种选择。

import matplotlib.pyplot as plt
import numpy as np 

fig = plt.figure(figsize=(10.0, 4.0))
axs = fig.subplots(2, 2)

xticklabels = [str(x) for x in range(0, 40+1, 5)]
y = np.random.rand(41*8)
ax0 = axs[0,0].twiny()
axs[0,0].set_xticks(np.arange(0,41*8,5*8))
axs[0,0].set_xticklabels(xticklabels)
ax0.set_xlim(axs[0,0].get_xlim())
ax0.set_xticks(np.arange(0,41*8,5*8))
ax0.set_xticklabels(xticklabels)

axs[0,0].plot(y)

plt.show()

编辑: 其实我想要这样的东西:

import matplotlib.pyplot as plt
import numpy as np 

fig = plt.figure(figsize=(10.0, 4.0))
axs = fig.subplots(2, 2)

xticklabels = [str(x) for x in range(0, 40+1, 5)]
y = np.random.rand(41*8)
ax0 = axs[0,0].twiny()
axs[0,0].set_xticks(np.arange(0,41*8,5*8))
axs[0,0].set_xticklabels(xticklabels)
ax0.set_xlim(axs[0,0].get_xlim())
ax0.set_xticks(np.arange(10*8,31*8,5*8))
ax0.set_xticklabels(["0", "25", "50", "75", "100"])

axs[0,0].plot(y)

plt.show()

但是您可以看到刻度不对齐。我快疯了!

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    如果您只想显示第二个 x 轴(而不在其上绘制任何内容),使用scondary axis 可能会更容易。您必须根据需要更改functions

    import matplotlib.pyplot as plt
    import numpy as np 
    
    y = np.random.rand(41*8)
    
    fig,ax = plt.subplots()
    ax.set_xticks(np.arange(0,41*8,5*8))
    xticklabels = [str(x) for x in range(0, 41, 5)]
    ax.set_xticklabels(xticklabels)
    
    secx = ax.secondary_xaxis('top', functions=(lambda x: x/8, lambda x: x/8))
    
    ax.plot(y)
    plt.show()
    


    我认为twiny 的问题是由于新轴上没有数据,但是 即使在手动设置数据间隔之后,我也无法让它工作。


    根据评论和编辑问题更新

    secx = ax.secondary_xaxis('top', functions=(lambda x: 5*x/8-50, lambda x: 5*x/8-50))
    secx.set_xticks([0,25,50,75,100])
    secx.set_xticklabels([f'{x}' for x in secx.get_xticks()])
    

    【讨论】:

    • 如果我只想在上轴 10-30 处添加刻度/标签,这是否有效?
    • 是的,正如我所说,你必须只采用函数:functions=(lambda x: 10 + x/16, lambda x: 10 + x/16)
    • 是的,但我只想在底部位置 10-30 的顶部打勾,并带有不同的标签:其中 10 位于底部,顶部应为 0,30 处应为 100,没有其他蜱虫。对不起,我做不到 :(
    • 请看我更新的答案。您可能需要将您的 matplotlib 更新到 3.2 或更高版本。
    【解决方案2】:

    好的,我现在的解决方法是简单地用第二个轴绘制数据,不带颜色。

    import matplotlib.pyplot as plt
    import numpy as np 
    
    
    fig,axs = plt.subplots()
    
    xticklabels = [str(x) for x in range(0, 40+1, 5)]
    y = np.random.rand(41*8)
    
    axs.set_xticks(np.arange(0,41*8,5*8))
    axs.set_xticklabels(xticklabels)
    ax0 = axs.twiny()
    
    ax0.set_xticks(np.arange(10*8,31*8,5*8))
    ax0.set_xticklabels(["0", "25", "50", "75", "100"])
    axs.plot(y)
    ax0.plot(y, color ="None")
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 2020-11-22
      • 2011-09-18
      • 1970-01-01
      • 2013-03-24
      • 2020-03-29
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多