In this Python Matplotlib tutorial, we will discuss the Matplotlib xlim. Here we will cover different examples related to the xlim function using matplotlib. And we will also cover the following topics:
- Matplotlib xlim
- Matplotlib call xlim
- Matplotlib xlim left
- Matplotlib xlim right
- Matplotlib xlim log scale
- Matplotlib scatter plot xlim
- Matplotlib xlim histogram
- Matplotlib imshow xlim
- Matplotlib heatmap xlim
- Matplotlib xlim padding
- Matplotlib 3d plot xlim
- Matplotlib animation xlim
- Matplotlib xlim errorbar
- Matplotlib twiny xlim
- Matplotlib xlim subplot
- Matplotlib xlim datetime
Table of Contents
Matplotlib xlim
In this section, we’ll learn about the xlim() function of the pyplot module of the matplotlib library. The xlim() function is used to set or get the x-axis limits or we can say x-axis range.
By default, matplotlib automatically chooses the range of x-axis limits to plot the data on the plotting area. But if you want to change that range of the x-axis limits then you can use the xlim() function.
So first, we’ll see the syntax of the xlim() function.
matplotlib.pyplot.xlim(*args, **kargs)
Here you can use arguments and keyword arguments, so we can have zero or multiple arguments and keyword arguments.
Also, check: Matplotlib x-axis label
Matplotlib call xlim
There we’ll learn to call the xlim() function of the pyplot module. Usually, we’ll call xlim() function in three different ways:
- Get current axis range
- Change current axis range
- Change current axis range with keyword arguments
Get current axis range
To get the current axis range you’ll have to take the two variables say left and right, so you’ll get the left value and right value of the range, and then you’ll call this xlim() function.
Syntax:
left, right = matplotlib.pyplot.xlim()
Let’s see an example:
# Import Libraryimport numpy as np import matplotlib.pyplot as plt# Data Coordinatesx = np.arange(2, 8) y = np.array([5, 8, 6, 20, 18, 30])# PLotplt.plot(x, y) # Get and print current axesleft, right = plt.xlim()print("Left value:",left,"\n","Right Value:",right)# Add Titleplt.title("Get Current axis range") # Add Axes Labelsplt.xlabel("X-axis") plt.ylabel("Y-axis") # Displayplt.show()
- Firstly, we import matplotlib.pyplot, and numpy libraries.
- Next, we define data coordinates for plotting, using arange() and array() function of numpy.
- To plot the graph, we use the plot() function.
- Take two variables left and right and xlim() function without any argument that means it will return the current x-axis range.
- Then we’ll get the left and right values, and print them using the print() function.
- To add title, we use the title() function.
- To add tha labels at axes, we use the xlabel() and ylabel() functions.
- To display the graph, we use the show() function.
Change current axis range
If you want to change the limits then, we call the xlim() function with the left value and right value of your choice.
Syntax:
matplotlib.pyplot.xlim(left_value, right_value)
Let’s see an example:
# Import Libraryimport numpy as npimport matplotlib.pyplot as plt# Define Datax = [0, 1, 2, 3, 4, 5]y = [1.5, 3, 5.3, 6, 10, 2]# Change current axesplt.xlim(2, 5)# Plotplt.plot(x,y,'-o')# Displayplt.show()
To change the value of the current x-axis, we use the xlim() function and pass the left and right values of your choice.
Change current axes range with keyword argument
Here you’ll use the xlim() function to change the axes range with keyword arguments instead of taking arguments.
Syntax:
matplotlib.pyplot.xlim(left=value, right=value)
Let’s see an example:
# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define data coordinatesx = np.linspace(20, 10, 100)y = np.sin(x)# Change axes with keyword argumentsplt.xlim(left=5, right=15)# Plotplt.plot(x, y)# Displayplt.show()
- Here we first import matplotlib.pyplot and numpy libraries.
- Next, we define data coordinates, using linespace() and sin() function of numpy.
- To change the limit of axes, we use the xlim() function with keyword arguments left and right and set their values. Here we set the left value as 5 and the right value is 15.
- To plot the line graph, we use the plot() function.
Read: Matplotlib multiple bar chart
Matplotlib xlim left
Here we’ll learn to set or get the limit of the left value of the x-axis. Let’s see different examples regarding this.
Example #1
In this example, we’ll get the left current axis limit and for this, we’ll take the variable left, and then we call the xlim() function without any argument.
Syntax:
left =matplotlib.pyplot.xlim()
Source Code:
# Import Libraryimport numpy as np import matplotlib.pyplot as plt# Data Coordinatesx = np.arange(2, 8) y = np.array([2, 4, 6, 8, 10, 12])# PLotplt.plot(x, y) # Get and print current axesleft, right= plt.xlim()print("Left value:",left)# Displayplt.show()
Output:
Example #2
In this example, we’ll set the left current axis limit and for this, we’ll take the keyword argument left with xlim() function.
Syntax:
matplotlib.pyplot.xlim(left=left_value)
Source Code:
# Import Libraryimport numpy as np import matplotlib.pyplot as plt# Data Coordinatesx = [1, 2, 3, 4, 5]y = [4, 8, 12, 16, 20]# PLotplt.plot(x, y) # Set left axesplt.xlim(left=2.5)# Displayplt.show()
Output:
Example #3
If you want to change the limits then, we call the xlim() function with the left value of your choice. The right value of the plot is set automatically.
Syntax:
matplotlib.pyplot.xlim(left_value)
Source Code:
# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define data coordinatesx = np.linspace(20, 10, 100)y = np.sin(x)# Change axesplt.xlim(20)# Plotplt.plot(x, y)# Displayplt.show()
Here we pass the 20 to xlim() function and this value is set as the left x-axis of the plot.
Output:
Read: Matplotlib scatter plot legend
Matplotlib xlim right
Here we’ll learn to set or get the limit of the right value of the x-axis. Let’s see different examples regarding this.
Example #1
In this example, we’ll get the right current axis limit and for this, we’ll take the variableright, and then we call thexlim()function without any argument. And after this, we print the right value.
Syntax:
right =matplotlib.pyplot.xlim()
Source Code:
# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define data coordinatesx = np.arange(5, 11) y = np.array([2, 4, 6, 8, 10, 12])# Plotplt.plot(x, y)# Get and print current axesleft, right= plt.xlim()print("Right value:",right)# Displayplt.show()
Output:
Example #2
In this example, we’ll set the right current axis limit and for this, we’ll take the keyword argumentrightwiththe xlim()function.
Syntax:
matplotlib.pyplot.xlim(right=right_value)
Source Code:
# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define data coordinatesx = np.random.randint(450,size=(80))y = np.random.randint(260, size=(80))# Plotplt.scatter(x, y)# Set right axesplt.xlim(right=250)# Displayplt.show()
Output:
Read: Matplotlib default figure size
Matplotlib xlim log scale
Here we’ll see an example of a log plot and here we also set the limits of the x-axis.
Let’s see an example:
# Import Libraryimport matplotlib.pyplot as plt # Define Datax = [ 10**i for i in range(5)]y = [ i for i in range(5)] # Log scaleplt.xscale("log")# Plotplt.plot(x,y)# Set limitplt.xlim([1,2**10])# Displayplt.show()
- Here we first import matplotlib.pyplot library.
- Next, we define data coordinates.
- Then we convert x-axis scale to log scale, by using xscale() function.
- To plot the graph, we use plot() function.
- To set the limits of x-axis, we use xlim() function.
- To display the graph, we use show() function.
Output:
Read: Stacked Bar Chart Matplotlib
Matplotlib scatter plot xlim
Here we’ll set the limit of the x-axis of the scatter plot. To create a scatter plot, we use the scatter() function, and to set the range of the x-axis we use the xlim() function.
Let’s see an example:
# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 20, 0.2)y = np.sin(x)# Plottingplt.scatter(x, y)# Set axesplt.xlim(6, 18)# Add labelplt.xlabel('X-Axis')plt.ylabel('Y-Axis')# Displayplt.show()
Here the minimum or right value of the x-axis approx 0.0 and the maximum or left value of the x-axis approx 20.0.
Here we set the right limit of the x-axis to 6 and the left limit of the x-axis to 18.
Read: Matplotlib two y axes
Matplotlib xlim histogram
Here we’ll learn to set limits of the x-axis in the histogram. First, we discuss what does histogram is. Basically, the histogram is a chart, which is used for frequency distribution. To create a histogram chart in matplotlib, we use the hist() function.
And we already know that to set the x-axis limits, we use xlim() function.
Example:
# Import Libraryimport numpy as npimport matplotlib.pyplot as plt# Define Datax = np.random.normal(170, 10, 250)# Plot Histogramplt.hist(x)# Set limitsplt.xlim(160,250)# Displayplt.show()
Here we set the maximum and minimum range of the x-axis to 160 and 250 respectively.
Read: Horizontal line matplotlib
Matplotlib imshow xlim
The imshow() function of matplotlib is used to display data as an image and to set the x-axis limits we, use the xlim() function.
Let’s see an example:
# Import Libraryimport numpy as npimport matplotlib.pyplot as plt# Define Datax = np.arange(100).reshape((10,10)) # Set axesplt.xlim(left=-1,right=10)# Heat mapplt.imshow( x, cmap = 'Set2' , interpolation = 'bilinear')# Add Titleplt.title( "Imshow Xlim Function" )# Displayplt.show()
- Import matplotlib.pyplot and numpy library.
- Next, we define data coordinates using arange() function of numpy.
- After this, we use xlim() function to set x-axis. We set the left value to -1 and the right value to 10.
- Then, we use theimshow()function to plot the heatmaps. We pass thexparameter to represent data of the image, thecmapparameter is the colormap instance, and theinterpolationparameter is used to display an image.
Read: Draw vertical line matplotlib
Matplotlib heatmap xlim
The heatmap() function of the seaborn module is used to plot rectangular data as a color matrix, and to set the x-axis limit, use the xlim() function.
Let’s see an example:
# Import Libraryimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # Define Data Coordinatesx = np.arange(15**2).reshape((15, 15))# HeatMapsns.heatmap( x , linewidth = 0.5 , cmap = 'tab10' )# Set limitplt.xlim(5,8)# Add Titleplt.title( "Heat Map" )# Displayplt.show()
- In the above example, we importnumpy,matplotlib.pyplot, andseabornlibrary.
- After this, we define data coordinates usingarange()method of numpy and reshape it usingreshape()method.
- Then we use theheatmap()function of the seaborn.
- To set the limits of x-axis, we use xlim() function with left and right value of the plot.
- To add a title to the plot, use thetitle()function.
Read: Put legend outside plot matplotlib
Matplotlib xlim padding
While setting the x-axis limit, we can preserve padding by using the tight layout. To set the tight layout, we use plt.rcParams[“figure.autolayout”] = False.
Example:
# Import Librariesimport numpy as npimport matplotlib.pyplot as plt# Setting plotplt.rcParams["figure.figsize"] = [6.00, 3.00]plt.rcParams["figure.autolayout"] = True# Define Datax = np.linspace(-20, 20, 300)y = np.cos(x)# Set axesplt.xlim([2,max(x)])# Plotplt.plot(x, y)# Display plt.show()
Explanation:
- First, import numpy and matplotlib.pyplot libraries.
- Next, to set the figure size, we use plt.rcParams[“figure.figsize”].
- To adjust the padding between and around the subplots, we use plt.rcParams[“figure.autolayout”].
- Create x and y data coordinates, using linspace() and cos() functions of numpy.
- Limit the x-axis, we use xlim() function.
- Using the plot() method, plot x and y data points.
- Use the show() function to display the figure
Read: Matplotlib title font size
Matplotlib 3d plot xlim
A 3D Scatter Plot is a mathematical diagram, used to display the properties of data as three variables using the cartesian coordinates. In matplotlib to create a 3D scatter plot, we have to import themplot3dtoolkit.
Here we learn to set the limit of the x-axis of the 3d plot, using the xlim() function of the pyplot module.
Example:
# Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt# Create Figurefig = plt.figure(figsize = (10, 7))ax = plt.axes(projection ="3d") # Define Datax = np.arange(0, 20, 0.2)y = np.sin(x)z = np.cos(x)# Create Plotax.scatter3D(x, y, z)# Limit Axesplt.xlim(left= -15) # Show plotplt.show()
- In the above example, we importmplot3d toolkits,numpy, andpyplotlibraries.
- plt.figure()method is used to set figure size here we passfigsizeas a parameter.
- plt.axes()method is used to set axes and here we passprojectionas a parameter.
- Next, we define data usingarange(),sin(), andcos()method.
- To set x-axis limits, we use plt.xlim() function. Here we set left value to -15 and right side value is adjusted automatically.
- ax.scatter3D()method is used to create 3D scatter plot, here we passx,y, andzas parameter.
- plt.show()method is used to generate graph on user screen.
Read: Matplotlib bar chart labels
Matplotlib animation xlim
Here we’ll see an example of an animation plot, where we set the limit of the x-axis by using the axes() function. We pass xlim as a parameter to the axes function.
Example:
# Import Librariesimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation# Create figure and axesfig = plt.figure()ax = plt.axes(xlim=(0,4))plot, = ax.plot([], [])# Define functionsdef init(): plot.set_data([], []) return line,def animate(i): x = np.linspace(0, 4, 100) y = np.sin(x*i) plot.set_data(x, y) return line,# Animationanim = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)# Save as gifanim.save('Animation Xlim.gif', writer='pillow')
- We import numpy, matplotlib.pyplot, and animation libraries.
- We define the init function, which is responsible for triggering the animation. The init function sets the axis bounds as well as initializes the data.
- Then, we define the animation function, which takes the frame number(i) as an argument and generates a sine wave with a shift based on i. This function returns a tuple of the changed plot objects, telling the animation framework which elements of the plot should be animated.
- By usinganimation.FuncAnimation()method we add animation to Plot.
- Then, at last, we use thesave()method to save a plot as agif.
Read: Matplotlib plot error bars
Matplotlib xlim errorbar
When we graphical represent the data, some of the data have irregularity. To indicate these irregularities or uncertainties we useError Bars. To set the limits of the x-axis, use the xlim() function of the pyplot module.
Example:
# Import Libraryimport matplotlib.pyplot as plt # Define Datax= [2, 4, 6, 8, 10]y= [9, 15, 20, 25, 13]# Plot error barplt.errorbar(x, y, xerr = 0.5)# Limit x-axisplt.xlim(0,8)# Display graphplt.show()
- In the above, example we import thematplotlib.pyplotlibrary.
- Then we define the x-axis and y-axis data points.
- plt.errorbar()method is used to plot error bars and we pass the argumentx, y,andxerrand set the value of xerr =0.5.
- To set the limits of x-axis, we use xlim() function. Here ranges lies between 0 to 8.
- Then we useplt.show()method to display the error bar plotted graph.
Read: Matplotlib rotate tick labels
Matplotlib twiny xlim
In matplotlib, thetwiny()function is used to create dual axes. To set the limit of the dual x-axis, we use the set_xlim() function.
Example:
# Import Libraryimport numpy as npimport matplotlib.pyplot as plt# Define Datax = np.arange(100)y = np.cos(x)# Plot Graphfig, ax1 = plt.subplots()ax1.plot(x, y)# Define Labelsax1.set_xlabel('X1-axis')ax1.set_ylabel('Y-axis')# Twin Axesax2 = ax1.twiny()ax2.set_xlim(-1,2)ax2.set_xlabel('X2-Axis')# Displayplt.show()
- Here we create two x-axes with the same data, so first, we import matplotlib. pyplot, and numpy libraries.
- Next, we define data coordinates using arange() and cos() function of numpy.
- To plot the graph, we use the plot() function of the axes module.
- To set the labels at axes, we use set_xlabel() and set_ylabel() functions.
- To create a twin x-axis, we use the twiny() function.
- To set the limits of x-axis, we use set_xlim() function.
Read: Matplotlib remove tick labels
Matplotlib xlim subplot
Here we’ll discuss how we can change the x-axis limit of the specific subplot if we draw multiple plots in a figure area.
Example:
# Importing Librariesimport numpy as npimport matplotlib.pyplot as plt# Create subplotfig, ax = plt.subplots(1, 2)# Define Datax1= [0.2, 0.4, 0.6, 0.8, 1]y1= [0.3, 0.6, 0.8, 0.9, 1.5]x2= [2, 6, 7, 9, 10]y2= [3, 4, 6, 9, 12]# Plot graphax[0].plot(x1, y1)ax[1].plot(x2, y2)# Limit axesax[1].set_xlim(0,10)# Add spacefig.tight_layout()# Display Graphplt.show()
- Firstly, we import numpy and matplotlib.pyplot libraries.
- After this, we create a subplot using subplots() function.
- Then we create x and y data coordinates.
- To plot a graph, we use the plot() function of the axes module.
- Here we change the x-axis limit of 1st subplot by using the set_xlim() function. It ranges between 0 to 10.
- To auto-adjust the space between subplots, we use the tight_layout() function.
- To display the graph, we use the show() function.
Read: Matplotlib change background color
Matplotlib xlim datetime
Here we’ll see an example where we create a date plot and set their x-axis limits manually.
Example:
# Import Librariesimport datetimeimport matplotlib.pyplot as plt# Subplotfig, ax = plt.subplots()# Define Datax = [datetime.date(2021, 12, 28)] * 3y = [2, 4, 1]# plot Dateax.plot_date(x, y)# Auto format datefig.autofmt_xdate()# Set x-limitsax.set_xlim([datetime.date(2021, 12, 20), datetime.date(2021, 12, 30)])# Displayplt.show()
- We import datetime and matplotlib.pyplot libraries.
- Then we create subplot, using subplots() function.
- Then we define data coordinates. Here we set x coordinates as dates.
- To plot the dates, we use plot_date() function.
- To auto format the dates at x-axis, we use autofmt_xdate() function.
- To set the limit of x-axis, we use set_xlim() function.
- To display the graph, we use the show() function.
You may also like to read the following tutorials on Matplotlib.
- Matplotlib dashed line – Complete Tutorial
- Matplotlib plot_date – Complete tutorial
- Matplotlib set y axis range
- Matplotlib update plot in loop
- Matplotlib Pie Chart Tutorial
In this Python tutorial, we have discussed the “Matplotlib xlim” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.
- Matplotlib xlim
- Matplotlib call xlim
- Matplotlib xlim left
- Matplotlib xlim right
- Matplotlib xlim log scale
- Matplotlib scatter plot xlim
- Matplotlib xlim histogram
- Matplotlib imshow xlim
- Matplotlib heatmap xlim
- Matplotlib xlim padding
- Matplotlib 3d plot xlim
- Matplotlib animation xlim
- Matplotlib xlim errorbar
- Matplotlib twiny xlim
- Matplotlib xlim subplot
- Matplotlib xlim datetime
Bijay Kumar
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.