【问题标题】:How to give same space for y axis tick labels in Matplotlib for different figures?如何在 Matplotlib 中为不同图形的 y 轴刻度标签提供相同的空间?
【发布时间】:2021-11-03 07:22:53
【问题描述】:

我需要使用相同的函数绘制图形。

Y 轴刻度标签可以是 2 位,有时是 3 位整数。

虽然我将 y 轴刻度标签格式化为 3 位整数,但左侧脊柱前的间距略有变化。

如何为 y 轴刻度标签提供相同的空间,以便轴的左脊椎在不同图形的相同位置开始?

这里是复制这些数字的示例代码:

from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import MaxNLocator

import numpy as np
import os

def plot_figure(start, end, figure_name):
    fwidth = 15
    fheight = 7

    fig = plt.figure(figsize=(fwidth, fheight), facecolor=None)
    plt.style.use('ggplot')

    # define margins
    left_margin = 0.95 / fwidth
    right_margin = 0.2 / fwidth
    bottom_margin = 0.5 / fheight
    top_margin = 0.25 / fheight

    # create axes
    x = left_margin  # horiz. position of bottom-left corner
    y = bottom_margin  # vert. position of bottom-left corner
    w = 1 - (left_margin + right_margin)  # width of axes
    h = 1 - (bottom_margin + top_margin)  # height of axes
    ax = fig.add_axes([x, y, w, h])

    ax.set_facecolor('white')

    # This code puts the edge line
    for edge_i in ['left', 'bottom','right', 'top']:
        ax.spines[edge_i].set_edgecolor("black")
        ax.spines[edge_i].set_linewidth(3)

    plus_minus = 50
    x = np.arange(-plus_minus, plus_minus + 1, 1)
    signal_array = np.random.randint(start, end + 1, size = 2*plus_minus+1)
    plt.plot(x, signal_array, color='b', label='Signal', linewidth=2, zorder=10)

    # This code puts the tick marks
    plt.tick_params(axis='both', which='major', labelsize=50, width=3, length=10)
    plt.tick_params(axis='both', which='minor', labelsize=50, width=3, length=10)

    # This code provides the x and y tick marks and labels
    plt.xticks(np.arange(-plus_minus/2, plus_minus/2+1, step=plus_minus/2), fontsize=50)
    plt.xlim((-plus_minus, plus_minus))

    ax.yaxis.set_major_formatter(FormatStrFormatter('%3d'))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2))
    ax.yaxis.set_major_locator(MaxNLocator(3))

    figure_file = os.path.join('/Users','burcakotlu','Desktop','test2.png')
    fig.savefig(figure_file, dpi=100, bbox_inches="tight")
    plt.close(fig)

plot_figure(20, 50, 'test1')
plot_figure(100, 130, 'test2')

【问题讨论】:

  • 不要调用 bbox_inches="tight"。这为艺术家修剪了人物。

标签: python matplotlib yaxis


【解决方案1】:

也许您应该考虑在同一 fig 内绘图并添加 sharex=True 选项,如下所示:

from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import MaxNLocator

import numpy as np
import os

fwidth = 15
fheight = 7

fig, axs = plt.subplots(2, 1, figsize=(fwidth, fheight), sharex=True, dpi=100)
plt.style.use('ggplot')


# This code provides the x and y tick marks and labels
plus_minus = 50
plt.xticks(np.arange(-plus_minus/2, plus_minus/2+1, step=plus_minus/2), fontsize=50)
plt.xlim((-plus_minus, plus_minus))

for i, se in enumerate([(20, 50), (100, 130)]):
    ax = axs[i]
    ax.set_facecolor('white')

    # This code puts the edge line
    for edge_i in ['left', 'bottom','right', 'top']:
        ax.spines[edge_i].set_edgecolor("black")
        ax.spines[edge_i].set_linewidth(3)
    

    x = np.arange(-plus_minus, plus_minus + 1, 1)
    signal_array = np.random.randint(se[0], se[1] + 1, size = 2*plus_minus+1)
    ax.plot(x, signal_array, color='b', label='Signal', linewidth=2, zorder=10)

    # This code puts the tick marks
    ax.tick_params(axis='both', which='major', labelsize=50, width=3, length=10)
    ax.tick_params(axis='both', which='minor', labelsize=50, width=3, length=10)

    ax.yaxis.set_major_formatter(FormatStrFormatter('%3d'))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2))
    ax.yaxis.set_major_locator(MaxNLocator(3))

plt.show()

【讨论】:

  • 不幸的是,在我的例子中,真正的代码必须绘制许多数字。数字的数量完全取决于数据。我必须制作相同大小的图形并在插图画家/编辑器中对齐。
【解决方案2】:

如果您知道数据在 y 轴上的范围,则可以使用 ylim 来确保 yticks 在绘图中均匀分布。 在此处查看代码:

from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import MaxNLocator

import numpy as np
import os

def plot_figure(start, end, figure_name):
    fwidth = 15
    fheight = 7

    fig = plt.figure(figsize=(fwidth, fheight), facecolor=None)
    plt.style.use('ggplot')

    # define margins
    left_margin = 0.95 / fwidth
    right_margin = 0.2 / fwidth
    bottom_margin = 0.5 / fheight
    top_margin = 0.25 / fheight

    # create axes
    x = left_margin  # horiz. position of bottom-left corner
    y = bottom_margin  # vert. position of bottom-left corner
    w = 1 - (left_margin + right_margin)  # width of axes
    h = 1 - (bottom_margin + top_margin)  # height of axes
    ax = fig.add_axes([x, y, w, h])

    ax.set_facecolor('white')

    # This code puts the edge line
    for edge_i in ['left', 'bottom','right', 'top']:
        ax.spines[edge_i].set_edgecolor("black")
        ax.spines[edge_i].set_linewidth(3)

    plus_minus = 50
    x = np.arange(-plus_minus, plus_minus + 1, 1)
    signal_array = np.random.randint(start, end + 1, size = 2*plus_minus+1)
    plt.plot(x, signal_array, color='b', label='Signal', linewidth=2, zorder=10)

    # This code puts the tick marks
    plt.tick_params(axis='both', which='major', labelsize=50, width=3, length=10)
    plt.tick_params(axis='both', which='minor', labelsize=50, width=3, length=10)

    # This code provides the x and y tick marks and labels
    plt.xticks(np.arange(-plus_minus/2, plus_minus/2+1, step=plus_minus/2), fontsize=50)
    plt.xlim((-plus_minus, plus_minus))
    
    plt.ylim([0,160])

    ax.yaxis.set_major_formatter(FormatStrFormatter('%3d'))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2))
    ax.yaxis.set_major_locator(MaxNLocator(3))

    figure_file = os.path.join('/Users','burcakotlu','Desktop','test2.png')
 
    plt.show()

plot_figure(20, 50, 'test1')
plot_figure(100, 130, 'test2')

输出给出:

【讨论】:

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