【问题标题】:Multiple lines of x tick labels in matplotlibmatplotlib 中的多行 x 刻度标签
【发布时间】:2013-12-30 05:18:59
【问题描述】:

我正在尝试制作类似于此 excel 示例的绘图:

我想知道在 x 刻度标签上是否还有第二层(例如“5 年统计摘要”)。我知道我可以使用\n 制作多行刻度标签,但我希望能够独立移动两个级别。

【问题讨论】:

  • 多轴的一个很好的例子在这里:stackoverflow.com/questions/7761778/… 这足够接近吗?
  • 这与我想要的类似,但我不希望有第二个物理 x 轴。我基本上想在第一个轴上添加第二行文本,无论第一个轴如何都可以移动。即“背景”始终位于同一位置,但“5 年总结”可以向左或向右移动,具体取决于向图中添加了多少图。
  • 隐藏第二个轴很容易。总体而言,您希望事情如何变化还不太清楚.. 什么被锁定了?您可以使用textannotateaxisspines(即使您没有显示与这两个关联的实际轴)。对您来说最简单的方法不是取决于您显示的图片,而是取决于您想要注册的不同项目的内容(无论是在缩放绘图时还是在更改输入时)。目前,这一切都不清楚(即,当你移动“5 年总结”时,移动了什么?)。

标签: python python-3.x matplotlib


【解决方案1】:

我发现的最佳解决方案是使用plt.annotate 函数。这里描述得很好:in the last comment

【讨论】:

    【解决方案2】:

    这就接近了:

    fig = plt.figure( figsize=(8, 4 ) )
    ax = fig.add_axes( [.05, .1, .9, .85 ] )
    ax.set_yticks( np.linspace(0, 200, 11 ) )
    
    xticks = [ 2, 3, 4, 6, 8, 10 ]
    xticks_minor = [ 1, 5, 7, 9, 11 ]
    xlbls = [ 'background', '5 year statistical summary', 'future build',
              'maximum day', '90th percentile day', 'average day' ]
    
    ax.set_xticks( xticks )
    ax.set_xticks( xticks_minor, minor=True )
    ax.set_xticklabels( xlbls )
    ax.set_xlim( 1, 11 )
    
    ax.grid( 'off', axis='x' )
    ax.grid( 'off', axis='x', which='minor' )
    
    # vertical alignment of xtick labels
    va = [ 0, -.05, 0, -.05, -.05, -.05 ]
    for t, y in zip( ax.get_xticklabels( ), va ):
        t.set_y( y )
    
    ax.tick_params( axis='x', which='minor', direction='out', length=30 )
    ax.tick_params( axis='x', which='major', bottom='off', top='off' )
    

    【讨论】:

      【解决方案3】:

      由于缺乏声誉,我无法评论 behzad 的回答。我发现他的解决方案非常有用,但我想我会分享它,而不是使用 set_y() 来控制垂直对齐,我只是添加了一个换行符来垂直偏移标签。所以,对于上面的例子:

      xlbls = [ 'background', '\n5 year statistical summary', 'future build',
            '\nmaximum day', '\n90th percentile day', '\naverage day' ]
      

      对我来说,这是保持多行标签和多层标签垂直对齐的更好解决方案。

      【讨论】:

        【解决方案4】:

        由于声誉问题,我也无法发表评论,但对 behzad 的回答有一个小问题。

        tick_params() 'bottom' 和 'top' 关键字采用布尔值,而不是字符串(至少对于 py3.6)。例如,对我使用 bottom = 'off' 仍然会产生刻度,而使用 bottom = False 会删除刻度。

        所以替换

        ax.tick_params(axis='x', which='major', bottom='off', top='off')

        ax.tick_params(axis='x', which='major', bottom=False, top=False)

        它有效!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-01
          • 2012-03-14
          • 2013-03-24
          • 1970-01-01
          • 2019-11-18
          • 1970-01-01
          • 2021-01-31
          • 2020-03-29
          相关资源
          最近更新 更多