【问题标题】:How to align xticks of multiple subplot vertically?如何垂直对齐多个子图的 xticks?
【发布时间】:2023-01-02 20:19:59
【问题描述】:

当我尝试从数据帧的特定行绘制 3 个子图时,我得到一个奇怪的结果,即第三个子图在 xticks 中具有不同的间距,即使图的开始似乎是正确的。 我认为这可能与数据有关,因为 FE 57 和 FE 59 都从接近 0 的指数开始,而 FE 66 星的指数为 3600。 有没有一种方法可以用从 0 开始的空白绘制所有图形,以便所有 xticks 彼此垂直对齐?

fig, axs = plt.subplots(3, 1)
ser = plotdf[(plotdf['CAN_address'] == 'FE 57') & (plotdf['CAN_cmd'] == 62)]['CAN_value_translated']
axs[0].plot(ser.index, ser.values)
axs[0].set_title('FE 57')

ser = plotdf[(plotdf['CAN_address'] == 'FE 59') & (plotdf['CAN_cmd'] == 62)]['CAN_value_translated']
axs[1].plot(ser.index, ser.values)
axs[1].set_title('FE 59')

ser = plotdf[(plotdf['CAN_address'] == 'FE 66') & (plotdf['CAN_cmd'] == 62)]['CAN_value_translated']
axs[2].plot(ser.index, ser.values)
axs[2].set_title('FE 66')

plt.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以使用 set_xlim() 设置轴的限制:

    x_min = -1000
    x_max = 51000
    
    for ax in axs:
      ax.set_xlim((x_min, x_max))
    

    【讨论】:

      【解决方案2】:

      要垂直对齐多个子图的 x 刻度,您可以先将所有子图的 xlim 设置为相同的值,以便它们都显示相同的 x 值范围。然后,您可以使用每个子图的 set_xticks 方法来指定 x 刻度的位置。

      # Set the x-limits of all subplots to be the same
      max_x = 3600
      
      for ax in axs:
          ax.set_xlim((0, max_x))
      
      # Set the number of x-ticks
      num_xticks = 10
      
      # Calculate the interval between x-ticks
      interval = max_x // num_xticks
      
      # Generate an array of x-tick values
      xticks = range(0, max_x+1, interval)
      
      # Set the x-ticks of all subplots to be the same
      for ax in axs:
          ax.set_xticks(xticks)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 2021-08-22
        • 2011-01-20
        • 2021-02-26
        • 1970-01-01
        • 2015-01-20
        • 2016-10-11
        相关资源
        最近更新 更多