Home > Software engineering >  How to give same space for y axis tick labels in Matplotlib for different figures?
How to give same space for y axis tick labels in Matplotlib for different figures?

Time:11-04

I need to plot figures using the same function.

Yaxis tick labels can be 2 digit and sometimes 3 digit integer numbers.

Although I format the y axis tick labels as 3 digit integers, spacing before the left spine slightly changes.

How to give same space for the y axis tick labels so that the left spine of the axis starts at the same location for different figures?

Here is the sample code to replicate these figures:

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('='))
    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')

enter image description here enter image description here

CodePudding user response:

Maybe you should consider to plot within the same fig and add sharex=True option with something like this:

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('='))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2))
    ax.yaxis.set_major_locator(MaxNLocator(3))

plt.show()

enter image description here

CodePudding user response:

If you know the range of your data on the y-axis, you could use ylim to ensure that the yticks are spaced evenly across plots. See code here:

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('='))
    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')

And the output gives:

enter image description here

enter image description here

  • Related