pythonmatplotlibvisualization

How to set matplotlib spacing when using xlim. Or is it possible to use margins() with xlim()?


Per default, matplotlib always adds whitespace between your first data points and the axis like you can see in the image: Default Plot with whitespace between data and axis. The following Code was used:

import matplotlib.pyplot as plt
data = [1, 2, 3, 4, 5]
fig, ax = plt.subplots()
ax.plot(data)
plt.show()

Now when I add a xlim with ax.set_xlim(2), then the spacing list gone:

Plot with xlim and no whitespace to yaxis

How can I limit the axes but also use spacing (so that the line does not touch the axes)?

Edit: So my desired output looks like this:

Plot with xlim and spacing

I tried to use margins(), but it seems like it does not work together with xlim/ylim regardless of the order I call them.


Solution

  • To plot only a subset of a dataset a good approach is to trim the data to what you need as that allows matplotlib's formatting to work as normal.

    import matplotlib.pyplot as plt
    import numpy as np
    

    I am using numpy for the arrange and speed for large datasets.

    data = [1, 2, 3, 4, 5] # some dataset
    

    This would work with any dataset with no extra work beyond adjusting your range.

    range_to_plot = (2,4) # setting a range to plot min and max values
    

    This range is a minimum and maximum value on the x axis to plot. Simply set to length of data for only setting a lower limit.

    x_values = np.arange(len(data)) # x values for the data
    data_to_plot = np.array(data, dtype=float) # data to plot
    
    data_to_plot[x_values < range_to_plot[0]] = np.nan # setting values outside the range to nan
    data_to_plot[x_values > range_to_plot[1]] = np.nan # setting values outside the range to nan
    

    Creating an array for the x axis values makes working with the axis more straight forward. Setting values in the data to plot to nan s if outside our set range on the x axis.

    fig, ax = plt.subplots()
    ax.plot(x_values, data_to_plot)
    ax.set_xlim(range_to_plot[0]-0.1, range_to_plot[1]+0.1)
    plt.show()
    

    Our set_xlim includes offsets outwith the range we have plotted to give a whitespace between the axis and the plotted line.

    This produces a graph like this:

    A line graph with a straight blue line at an upward slope of 45 degrees