【问题标题】:Set xticks relative to the plot coordinates相对于绘图坐标设置 xticks
【发布时间】:2021-06-24 17:17:13
【问题描述】:

对于在 x 轴上具有不同范围的两个图,是否有一种简单的方法可以在距离 xmin 和 xmax 等距离处设置两个 xticks?

# Example: 
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(6,4), constrained_layout=True)
gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)

x1 = [1,   0.6,  0.4,  0.3,  0.25,   0.24,   0.23]
x2 = [0.1, 0.14, 0.15, 0.16, 0.166,  0.1666, 0.1666 ]
y  = [1, 2, 3, 4, 5, 6, 7]

# xticks 
number_of_xticks = 2

# Plot 1:
ax0 = fig.add_subplot(gs[0, 0]) 
ax0.plot(x1, y)
ax0.xaxis.set_major_locator(plt.MaxNLocator(number_of_xticks))

# Plot 2:
ax1 = fig.add_subplot(gs[0, 1]) 
ax1.plot(x2, y)
ax1.xaxis.set_major_locator(plt.MaxNLocator(number_of_xticks))

plt.show()

示例代码不起作用,因为 xticks 与两个图中的 xmin 和 xmax 的距离不同:

【问题讨论】:

    标签: python matplotlib xticks


    【解决方案1】:

    您可以尝试指定沿 x 范围的相对距离:

    # xticks 
    tick_fractions = [1/4, 3/4]
    

    然后根据每个x-range计算tick位置:

    mini = min(x)
    maxi = max(x)
    dist = maxi - mini
    ax.set_xticks([mini + f * dist for f in tick_fractions])
    

    所以完整的脚本看起来像:

    # Example: 
    from matplotlib import pyplot as plt
    import matplotlib.gridspec as gridspec
    
    fig = plt.figure(figsize=(6,4), constrained_layout=True)
    gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)
    
    x1 = [1,   0.6,  0.4,  0.3,  0.25,   0.24,   0.23]
    x2 = [0.1, 0.14, 0.15, 0.16, 0.166,  0.1666, 0.1666 ]
    y  = [1, 2, 3, 4, 5, 6, 7]
    
    # xticks 
    tick_fractions = [1/4, 3/4]
    
    # Plot 1:
    ax0 = fig.add_subplot(gs[0, 0]) 
    ax0.plot(x1, y)
    mini = min(x1)
    maxi = max(x1)
    dist = maxi - mini
    ax0.set_xticks([mini + f * dist for f in tick_fractions])
    
    # Plot 2:
    ax1 = fig.add_subplot(gs[0, 1]) 
    ax1.plot(x2, y)
    mini = min(x2)
    maxi = max(x2)
    dist = maxi - mini
    ax1.set_xticks([mini + f * dist for f in tick_fractions])
    
    plt.show()
    

    如果您想限制小数,可以在某处添加对 round 的调用。

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多