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
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 Library
import numpy as np
import matplotlib.pyplot as plt
# Data Coordinates
x = np.arange(2, 8)
y = np.array([5, 8, 6, 20, 18, 30])
# PLot
plt.plot(x, y)
# Get and print current axes
left, right = plt.xlim()
print("Left value:",left,"\n","Right Value:",right)
# Add Title
plt.title("Get Current axis range")
# Add Axes Labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Display
plt.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 Library
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = [0, 1, 2, 3, 4, 5]
y = [1.5, 3, 5.3, 6, 10, 2]
# Change current axes
plt.xlim(2, 5)
# Plot
plt.plot(x,y,'-o')
# Display
plt.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 Library
import matplotlib.pyplot as plt
import numpy as np
# Define data coordinates
x = np.linspace(20, 10, 100)
y = np.sin(x)
# Change axes with keyword arguments
plt.xlim(left=5, right=15)
# Plot
plt.plot(x, y)
# Display
plt.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 Library
import numpy as np
import matplotlib.pyplot as plt
# Data Coordinates
x = np.arange(2, 8)
y = np.array([2, 4, 6, 8, 10, 12])
# PLot
plt.plot(x, y)
# Get and print current axes
left, right= plt.xlim()
print("Left value:",left)
# Display
plt.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 Library
import numpy as np
import matplotlib.pyplot as plt
# Data Coordinates
x = [1, 2, 3, 4, 5]
y = [4, 8, 12, 16, 20]
# PLot
plt.plot(x, y)
# Set left axes
plt.xlim(left=2.5)
# Display
plt.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 Library
import matplotlib.pyplot as plt
import numpy as np
# Define data coordinates
x = np.linspace(20, 10, 100)
y = np.sin(x)
# Change axes
plt.xlim(20)
# Plot
plt.plot(x, y)
# Display
plt.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 variable right, and then we call the xlim() function without any argument. And after this, we print the right value.
Syntax:
right =matplotlib.pyplot.xlim()
Source Code:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define data coordinates
x = np.arange(5, 11)
y = np.array([2, 4, 6, 8, 10, 12])
# Plot
plt.plot(x, y)
# Get and print current axes
left, right= plt.xlim()
print("Right value:",right)
# Display
plt.show()
Output:
Example #2
In this example, we’ll set the right current axis limit and for this, we’ll take the keyword argument right with the xlim() function.
Syntax:
matplotlib.pyplot.xlim(right=right_value)
Source Code:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define data coordinates
x = np.random.randint(450,size=(80))
y = np.random.randint(260, size=(80))
# Plot
plt.scatter(x, y)
# Set right axes
plt.xlim(right=250)
# Display
plt.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 Library
import matplotlib.pyplot as plt
# Define Data
x = [ 10**i for i in range(5)]
y = [ i for i in range(5)]
# Log scale
plt.xscale("log")
# Plot
plt.plot(x,y)
# Set limit
plt.xlim([1,2**10])
# Display
plt.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 Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0, 20, 0.2)
y = np.sin(x)
# Plotting
plt.scatter(x, y)
# Set axes
plt.xlim(6, 18)
# Add label
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
# Display
plt.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 Library
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = np.random.normal(170, 10, 250)
# Plot Histogram
plt.hist(x)
# Set limits
plt.xlim(160,250)
# Display
plt.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 Library
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = np.arange(100).reshape((10,10))
# Set axes
plt.xlim(left=-1,right=10)
# Heat map
plt.imshow( x, cmap = 'Set2' , interpolation = 'bilinear')
# Add Title
plt.title( "Imshow Xlim Function" )
# Display
plt.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 the imshow() function to plot the heatmaps. We pass the x parameter to represent data of the image, the cmap parameter is the colormap instance, and the interpolation parameter 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 Library
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Define Data Coordinates
x = np.arange(15**2).reshape((15, 15))
# HeatMap
sns.heatmap( x , linewidth = 0.5 , cmap = 'tab10' )
# Set limit
plt.xlim(5,8)
# Add Title
plt.title( "Heat Map" )
# Display
plt.show()
- In the above example, we import numpy, matplotlib.pyplot, and seaborn library.
- After this, we define data coordinates using arange() method of numpy and reshape it using reshape() method.
- Then we use the heatmap() 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 the title() 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 Libraries
import numpy as np
import matplotlib.pyplot as plt
# Setting plot
plt.rcParams["figure.figsize"] = [6.00, 3.00]
plt.rcParams["figure.autolayout"] = True
# Define Data
x = np.linspace(-20, 20, 300)
y = np.cos(x)
# Set axes
plt.xlim([2,max(x)])
# Plot
plt.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 the mplot3d toolkit.
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 libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
# Create Figure
fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
# Define Data
x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
# Create Plot
ax.scatter3D(x, y, z)
# Limit Axes
plt.xlim(left= -15)
# Show plot
plt.show()
- In the above example, we import mplot3d toolkits, numpy, and pyplot libraries.
- plt.figure() method is used to set figure size here we pass figsize as a parameter.
- plt.axes() method is used to set axes and here we pass projection as a parameter.
- Next, we define data using arange(), sin(), and cos() 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 pass x, y, and z as 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 Libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create figure and axes
fig = plt.figure()
ax = plt.axes(xlim=(0,4))
plot, = ax.plot([], [])
# Define functions
def 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,
# Animation
anim = FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
# Save as gif
anim.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 using animation.FuncAnimation() method we add animation to Plot.
- Then, at last, we use the save() method to save a plot as a gif.
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 use Error Bars. To set the limits of the x-axis, use the xlim() function of the pyplot module.
Example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [2, 4, 6, 8, 10]
y= [9, 15, 20, 25, 13]
# Plot error bar
plt.errorbar(x, y, xerr = 0.5)
# Limit x-axis
plt.xlim(0,8)
# Display graph
plt.show()
- In the above, example we import the matplotlib.pyplot library.
- Then we define the x-axis and y-axis data points.
- plt.errorbar() method is used to plot error bars and we pass the argument x, y, and xerr and 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 use plt.show() method to display the error bar plotted graph.
Read: Matplotlib rotate tick labels
Matplotlib twiny xlim
In matplotlib, the twiny() function is used to create dual axes. To set the limit of the dual x-axis, we use the set_xlim() function.
Example:
# Import Library
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = np.arange(100)
y = np.cos(x)
# Plot Graph
fig, ax1 = plt.subplots()
ax1.plot(x, y)
# Define Labels
ax1.set_xlabel('X1-axis')
ax1.set_ylabel('Y-axis')
# Twin Axes
ax2 = ax1.twiny()
ax2.set_xlim(-1,2)
ax2.set_xlabel('X2-Axis')
# Display
plt.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 Libraries
import numpy as np
import matplotlib.pyplot as plt
# Create subplot
fig, ax = plt.subplots(1, 2)
# Define Data
x1= [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 graph
ax[0].plot(x1, y1)
ax[1].plot(x2, y2)
# Limit axes
ax[1].set_xlim(0,10)
# Add space
fig.tight_layout()
# Display Graph
plt.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 Libraries
import datetime
import matplotlib.pyplot as plt
# Subplot
fig, ax = plt.subplots()
# Define Data
x = [datetime.date(2021, 12, 28)] * 3
y = [2, 4, 1]
# plot Date
ax.plot_date(x, y)
# Auto format date
fig.autofmt_xdate()
# Set x-limits
ax.set_xlim([datetime.date(2021, 12, 20),
datetime.date(2021, 12, 30)])
# Display
plt.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
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.