【问题标题】:How can I remove xtics from an axis in matplotlib? [duplicate]如何从 matplotlib 中的轴中删除 xtics? [复制]
【发布时间】:2013-08-15 16:34:44
【问题描述】:

我在 matplotlib 中使用子图。由于我所有的子图都具有相同的 x 轴,因此我只想在底部图上标记 x 轴。如何从一个轴上移除 xtics?

【问题讨论】:

  • 您想去掉刻度标签,还是去掉实际的刻度线本身?如果只是标签,请查看演示 here,其中有几个使用子图的示例。
  • 我想只是标签。
  • @Bill:该演示使用 matplotlib.pyplot。有没有办法直接作用于figure 对象?

标签: python matplotlib axis-labels


【解决方案1】:

正如here 指出的那样,以下工作!

plt.tick_params(\
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='off',      # ticks along the bottom edge are off
    top='off',         # ticks along the top edge are off
    labelbottom='off') # labels along the bottom edge are off

【讨论】:

    【解决方案2】:

    Dan,如果您已经使用 OOP 方式设置了地块

    import matplotlib.pyplot as plt
    fig, ax_arr = subplots(3, 1, sharex=True)
    

    那么使用类似的东西隐藏 x 轴标签应该很容易

    plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
    # or
    plt.setp([a.get_xticklabels() for a in ax_arr[:-1]], visible=False)
    

    但请查看this link,一些更进一步的示例将证明是有用的。

    编辑:

    如果你不能使用plt.subplots(),我仍然认为你可以使用

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)
    
    ax1.plot(x1, y1)
    ax2.plot(x2, y2)
    
    plt.setp(ax1.get_xticklabels(), visible=False)
    

    如果你有2个以上的子图,比如

    ax1 = fig.add_subplot(N11)
    ax2 = fig.add_subplot(N12)
    ...
    axN = fig.add_subplot(N1N)
    
    plt.setp([a.get_xticklabels() for a in (ax1, ..., axN-1)], visible=False)
    

    【讨论】:

    • 我的matplotlib版本没有plt.subplots()。
    • @Dan,你的 matplotlib 版本允许你做fig = plt.figure(),ax = fig.add_subplot(111)吗?
    • 是的。这就是我目前正在做的子情节
    • 为什么将子图放在211 和222?这些数字分别用于 nrows、ncols 和 plot_number。这将导致ax2 覆盖ax1 的右半部分,以及它们下方的空行。另外,我认为N2N 应该是N1N、N21->N11 和N22->N12。也就是说,如果您试图让一列子图相互堆叠。
    • 是的,我的错。我总是很困惑,需要查一下。我通常只使用f, axarr = plt.subplots()。
    猜你喜欢
    • 2015-12-15
    • 2010-10-29
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2020-02-16
    相关资源
    最近更新 更多