Matplotlib X-axis Label - Python Guides (2024)

In this Python tutorial, we will discuss the Matplotlib x-axis label in python. Here we will cover different examples related to the x-axis label using matplotlib. And we will also cover the following topics:

  • Matplotlib x-axis label
  • Matplotlib x-axis label example
  • Matplotlib x-axis label size
  • Matplotlib x-axis label color
  • Matplotlib x-axis label vertical
  • Matplotlib x-axis label date
  • Matplotlib x-axis label spacing
  • Matplotlib x-axis label bold
  • Matplotlib x-axis label range
  • Matplotlib x-axis label remove
  • Matplotlib x-axis label scientific notation
  • Matplotlib x-axis tick label
  • Matplotlib x-axis label string
  • Matplotlib x-axis tick label size
  • Matplotlib x-axis tick label color
  • Matplotlib x-axis label subplot
  • Matplotlib x-axis label on top
  • Matplotlib x-axis label position
  • Matplotlib x-axis label overlap
  • Matplotlib disable x-axis label
  • Matplotlib move x-axis label down
  • Matplotlib x-axis label frequency
  • Matplotlib x-axis label rotation
  • Matplotlib x-axis label orientation
  • Matplotlib rotate x-axis label subplot
  • Matplotlib replace x-axis label
  • Matplotlib reduce x-axis label

Table of Contents

Matplotlib x-axis label

In this section, you will learn about x-axis labels in Matplotlib in Python. Before you begin, you must first understand what the term x-axis and label mean:

X-axis is one of the axes of a two-dimensional or three-dimensional chart. Basically, it is a line on a graph that runs horizontally through zero.

Labels are either numbers that represent an axis’ scale or the text that describes the categories.

The following are the steps to add x-axis labels to your graph:

  • Importing Libraries: Import the important libraries like Numpy and Pandas for data creation and pyplot from matplotlib for data visualization.
  • Define Data: Define the data coordinates that will be used to visualize the data.
  • Drawing Graph or Chart: You may draw a graph using the plot(), bar(), scatter(), and other functions.
  • Add x-axis label: Use the xlabel() method to add an x-axis label.
  • Generate graph: To display a graph on the user screen, use the show() method.

The following is the syntax for adding an x-axis label :

matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, loc=None , **kwargs)

The following are the parameters that were used:

  • xlabel: Indicates the text of the label.
  • labelpad: Specify space, in points, from the bounding box of the axes, including ticks and tick labels.
  • loc: Specify the location of the label.
  • kwargs: Text properties that control the label’s appearance.

Also, read: Matplotlib scatter marker

Matplotlib x-axis label example

Use the xlabel() method in matplotlib to add a label to the plot’s x-axis.

Let’s have a look at an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax = [0, 1, 2, 3, 4]y = [2, 4, 6, 8, 12]# Plottingplt.plot(x, y)# Add x-axis labelplt.xlabel('X-axis Label')# Visualizeplt.show()
  • In the above example, we import matplotlib.pyplot package and define the data coordinates for plotting.
  • After that, the plot() method is used to draw a line between y and x.
  • The xlabel() method is used to set the x-axis label.
  • The show() function is used to display the figure.
Matplotlib X-axis Label - Python Guides (1)

Read: Matplotlib dashed line

Matplotlib x-axis label size

We’ll look at how to make the x-axis label font bigger. To change the size, the fontsize parameter is passed to the xlabel() method.

The following is the syntax for changing the size of the x-axis labels:

matplotlib.pyplot.xlabel(xlabel, fontsize)

The label text is set by xlabel, while the font size is specified by fontsize.

Example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax = [0, 1, 2, 3, 4]y = [2, 10, 6, 5, 12]# Plottingplt.plot(x, y, '--')# Add x-axis labelplt.xlabel('X-axis Label', fontsize=20)# Visualizeplt.show()

The fontsize parameter is passed to the xlabel() method in the above example to adjust the size of the x-axis label. We assigned it a value of 20.

Matplotlib X-axis Label - Python Guides (2)

Read: Matplotlib plot_date

Matplotlib x-axis label color

We’ll learn how to modify the color of the x-axis label in this section. We use the color argument to customize its color.

Let’s look at an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax = [0, 1, 2, 3, 4]y = [2, 10, 6, 5, 12]# Plottingplt.plot(x, y, '--')# Add x-axis labelplt.xlabel('X-axis Label', fontsize=15, color='r')# Visualizeplt.show()

To change the color of the x-axis label, we pass a color parameter to the xlabel() method in the example above. We’ve changed the color to red.

Matplotlib X-axis Label - Python Guides (3)

Read: Matplotlib log log plot

Matplotlib x-axis label vertical

We’ll learn how to make the x-axis label vertical in this section. The rotation parameter is used to orient the label vertically.

The following is the syntax for setting the x-axis label vertically:

matplotlib.pyplot.xlabel(xlabel, rotation='vertical')

Example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 20, 0.2)y = np.sin(x)# Plottingplt.plot(x, y, '--')# Add x-axis labelplt.xlabel('Time', size = 15, rotation='vertical')# Visualizeplt.show()

Set the value of the rotation parameter to vertical in the example above. The x-axis label will be rotated in a vertical orientation.

Matplotlib X-axis Label - Python Guides (4)

Read: Matplotlib subplots_adjust

Matplotlib x-axis label date

We’ll learn how to add a date as a label on the x-axis here.

Let’s see an example:

# Import Librariesimport pandas as pdfrom datetime import datetime, timedeltafrom matplotlib import pyplot as pltfrom matplotlib import dates as mpl_dates# Define Datadates = [ datetime(2021, 10, 21), datetime(2021, 7, 24), datetime(2021, 8, 25), datetime(2021, 10, 26),]y = [ 0, 1, 2, 3]# Plottingplt.plot_date(dates, y)# Avoid overlappingplt.gcf().autofmt_xdate()# Visualizeplt.show()

The plot date() method is used to plot the date graph in the example above. The autofmt xdate() function is used here to automatically adjust the x-axis, which is composed of dates.

Matplotlib X-axis Label - Python Guides (5)

Matplotlib x-axis label spacing

We’ll learn how to add space between the x-axis labels in this section. To add space, the labelpad parameter is passed to the xlabel() method.

The following is the syntax:

matplotlib.pyplot.xlabel(xlabel, labelpad=None)

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 30, 0.5)y = np.cos(x)# Plottingplt.plot(x, y, '--')# Label spacingplt.xlabel('X-Axis') # ORplt.xlabel('X-Axis', labelpad=30) # ORplt.xlabel('X-Axis', labelpad=60)# Visualizeplt.show()

To provide spacing, we pass the labelpad parameter to the xlabel() method in the example above.

Matplotlib X-axis Label - Python Guides (6)
Matplotlib X-axis Label - Python Guides (7)
Matplotlib X-axis Label - Python Guides (8)

Read: Matplotlib best fit line

Matplotlib x-axis label bold

We’ll learn how to make x-axis labels bold in this topic. Pass the fontweight parameter to the xlabel() function to make the label bold.

The following is the syntax:

matplotlib.pyplot.xlabel(xlabel, fontweight='bold')

Let’s have a look at an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax = [0, 1, 2, 3, 4]y = [2, 10, 6, 9, 8.5]# Plottingplt.plot(x, y, '--')# Bold x-axis labelplt.xlabel('X-Axis Label', fontweight='bold')# Visualizeplt.show()
  • We import the matplotlib.pyplot package in the example above.
  • The next step is to define data and create graphs.
  • plt.xlabel() method is used to create an x-axis label, with the fontweight parameter we turn the label bold.
Matplotlib X-axis Label - Python Guides (9)

Read: Matplotlib subplot tutorial

READ: How to create Email sender app in Django?

Matplotlib x-axis label range

We’ll learn how to limit the range of the plot’s x-axis in this section. The xlim() method is used to set the x-axis limit.

The following is the syntax:

matplotlib.pyplot.xlim(limit_range)

Let’s take an example where we set x-axis label range:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 30, 0.5)y = np.cos(x)# Plottingplt.plot(x, y)# Add x-axis labelplt.xlabel('X-Axis')# x-axis limitplt.xlim(-2.5, 6)# Displayplt.show()
  • We import matplotlib.pyplot and the numpy library in the example above.
  • Following that, we use the arange() and cos() functions to define data.
  • To plot a graph, use the plt.plot() method.
  • To add labels to the x-axis, use the plt.xlabel() method.
  • The x-axis range is set using the plt.xlim() method. We altered it from -2.5 to 6 in this case.
Matplotlib X-axis Label - Python Guides (10)
Matplotlib X-axis Label - Python Guides (11)

Read: Matplotlib plot bar chart

Matplotlib x-axis label remove

We’ll learn how to get rid of the x-axis label in this part. We remove the entire x-axis label, including the text label, tick label, and tick markings.

We have to call the set_visible() method and set its value to False to remove the x-axis label.

The following is the syntax for removing the x-axis label:

matplotlib.axes.Axes.get_xaxis().set_visible(False)

Example:

# Import Libraryimport matplotlib.pyplot as plt# Create Figure and Axes fig,ax = plt.subplots(1)# Define Datax = np.arange(0, 30, 0.5)y = np.cos(x)# Make your plotax.plot(x, y)# Add labels ax.set_xlabel('X Label') ax.set_ylabel('Y Label') # Remove X labelplt.gca().axes.get_xaxis().set_visible(False) # Display plt.show()
  • To set the x-axis and y-axis labels, we use the ax.set_xlabel() and ax.set_ylabel() methods in the example above.
  • The current axes are then retrieved using the plt.gca() method.
  • The x-axis is then obtained using the axes.get_xaxis() method.
  • Then, to remove the x-axis label, we use set_visible() and set its value to False.
Matplotlib X-axis Label - Python Guides (12)

Matplotlib x-axis label scientific notation

We’ll learn how to format x-axis axes in scientific notation in this topic.

” Scientific Notation ” refers to a multipler for the number show.

Scientific Notation does not have plus signs as multipliers.

The ticklabel_format() method is used to convert an x-axis to scientific notation.

The following is the syntax:

matplotlib.pyplot.ticklabel_format(axis=None, style="", scilimits=None)

The following are the parameters that were used:

  • axis: specify the axis.
  • style: indicate the axis’s style.
  • scilimits: specify the scale’s bounds

Let’s have a look at an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax = [1000, 2000, 3000]y = [3000, 4000, 5000]# Plotplt.plot(x, y)# Scientific Notationplt.ticklabel_format(axis="x", style="sci", scilimits=(0,0))# Displayplt.show()

To convert the x-axis scale to scientific notation, we use the ticklabel_format() method and pass axis as x and style as a scientific notation.

Matplotlib X-axis Label - Python Guides (13)

Read: What is matplotlib inline

Matplotlib x-axis tick label

We’ll show you how to add tick labels on the x-axis of your choice.

Tick Labels are the markers on the axes that indicate the data points.

To add tick labels, use the following syntax:

matplotlib.axes.Axes.set_xticklabels(self,xlabel,fontdict=None,labelpad=None)

The following are the parameters that were used:

  • xlabel: the label text is specified.
  • fontdict: dictionary of font styles.
  • labelpad: space between the points.

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define datax = [1, 2, 3, 4, 5]y = [2.5, 0.6, 4.9, 3, 6]# Create subplotax = plt.subplot()# Define tick labelax.set_xticklabels([2, 4, 6, 8, 10])# Display graphplt.show()
  • We import matplotlib.pyplot and numpy libraries in the example above.
  • Then, for visualizing, we define data coordinates.
  • The plt.subplot() method is then used to construct a subplot.
  • The set_xticklabels() method is then used to define x- tick labels.

Output:

Matplotlib X-axis Label - Python Guides (14)

When we don’t specify tick labels, we get the output shown above.

Matplotlib X-axis Label - Python Guides (15)

When we choose tick labels, we get the output shown above.

Matplotlib x-axis label string

We’ll learn how to use a string to set an x-axis label or tick markers. The graph between programmers and languages is constructed.

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Dataprogrammers = [5, 6, 2, 3]languages = ["Python", "Java", "C++", "C" ]# Plot chartplt.plot( languages, programmers, color= 'r', marker= 'o')# Display chartplt.show()
  • We define x-axis labels in string form in the above example by putting them in quotation marks.
  • We use double quotation marks to define distinct languages so that they can be represented in string format.
  • After that, we plot a graph using the plt.plot() method, passing the color and marker as parameters and assig them red and o as a value respectively.
Matplotlib X-axis Label - Python Guides (16)

Read: Python plot multiple lines using Matplotlib

Matplotlib x-axis tick label size

The size of data axis labels, commonly known as tick labels, can be changed. We only need to pass the fontsize parameter and set its value.

To modify the size of an x tick label, use the following syntax:

matplotlib.pyplot.xticks(fontsize=)

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datastudents = [6, 15, 8, 10]color = ["Red", "Black", "White", "Blue"]# Plot sactter chartplt.scatter(color, students, marker='*', color='g', s=50)# Fontsize of tick labelsplt.xticks(fontsize=15)# Labelsplt.xlabel("Favourite color")plt.ylabel("No.of.students") # Display chartplt.show()
  • We import the matplotlib.pyplot package in the example above.
  • Following that, we define the data that will be plotted.
  • The plt.scatter() method is used to plot a scatter chart, and the arguments marker, color, and s are used to set the marker style, color, and size, respectively.
  • The plt.xticks() method is used to plot tick labels, and the fontsize parameter is adjusted to 15 to change the font size.
  • To set labels on the x-axis and y-axis, use the plt.xlabel() and plt.ylabel() methods.
Matplotlib X-axis Label - Python Guides (17)

Matplotlib x-axis tick label color

We’ll learn how to modify the color of tick labels on the x-axis in this section. To alter the color, use the xticks() method with a color parameter.

The following is the syntax for changing the color of x ticks:

matplotlib.pyplot.xticks(color=None)

Let’s have a look at an example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 30, 0.5)y = np.tan(x)# Plottingplt.plot(x, y)# Change color of xticksplt.xticks(color='r')# Visualizeplt.show()
  • In the above example, we use numpy’s arange() and tan() methods to define data and plot a graph between them.
  • To modify the color of the ticks, we use plt.xticks() and pass a color argument. The colour of xticks is set to red in this case.
Matplotlib X-axis Label - Python Guides (18)

Read: Matplotlib title font size

Matplotlib x-axis label subplot

We’ll learn how to add x-axis labels to the subplot here. To add labels to the x-axis, we use the set_xlabel() method.

The following is the syntax for adding a label to the x-axis:

matplotlib.axes.Axes.set_xlabel()

Example:

# Import Libraryimport matplotlib.pyplot as plt# 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]x3= [5, 8, 12]y3= [3, 6, 9]x4= [7, 8, 15]y4= [6, 12, 18]# Add subplotsfig, ax = plt.subplots(2, 2)# Add labels at x-axisax[0, 0].set_xlabel('Subplot 1')ax[0, 1].set_xlabel('Subplot 2')ax[1, 0].set_xlabel('Subplot 3')ax[1, 1].set_xlabel('Subplot 4')# Plot graphax[0, 0].plot(x1, y1)ax[0, 1].plot(x2, y2)ax[1, 0].plot(x3, y3)ax[1, 1].plot(x4, y4)# Display Graphfig.tight_layout()plt.show()
  • We plot multiple plots in a figure area and want to add a label to the x-axis in the example above.
  • To add labels, we use the set_xlabel() method.
Matplotlib X-axis Label - Python Guides (19)

Matplotlib x-axis label on top

We’ll learn how to put an x-axis label or x-axis tick marker to the top of the chart rather than the bottom.

READ: What is NumPy in Python

Tick and tick labels will be added on the left and bottom axes by default. We can turn on and off the labels independently in matplotlib.

The following is the syntax for adding a label to the top:

# Tick Markermatplotlib.axes.Axes.tick_params(bottom=True, top=False, left=True, right=False)# Tick Labelmatplotlib.axes.Axes.tick_params(labelbottom=True, labeltop=False, labelleft=True, labelright=False) 

The following are the boolean arguments:

  • bottom: specify whether the bottom ticks are shown or not.
  • top: specify whether the top ticks are shown or not.
  • right: specify whether the right ticks are shown or not.
  • left: specify whether the left ticks are shown or not.
  • labelbottom: specify whether the tick labels are shown at the bottom or not.
  • labeltop: specify whether the tick labels are shown at the top or not.
  • labelleft: specify whether the tick labels are shown at the left or not.
  • labelright: specify whether the tick labels are shown at the right or not.

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 30, 0.2)y = np.tan(x)# Add subplotax = plt.subplot()# Plottingplt.plot(x, y)# Xlabel on topax.tick_params(top=True, bottom=False)ax.tick_params(labeltop=True, labelbottom=False)# Visualizeplt.show()
  • We import matplotlib.pyplot and the numpy library in the code above.
  • Following that, we use the arange() and numpy’s tan() methods to specify data, then the plot() method to plot the graph.
  • To add ticks and tick labels, use the ax.tick_params() method.
  • To turn on ticks on the top of the axes and turn off ticks on the bottom of the axes, we pass top and bottom as parameters. To show tick labels at the top of the axes and hide tick labels from the bottom of the axes, we must pass labeltop and labelbottom as arguments.
Matplotlib X-axis Label - Python Guides (20)

Read: Matplotlib default figure size

Matplotlib x-axis label position

We’ll learn how to move the x-axis label to a different location or position in this topic.

The following is the syntax:

matplotlib.axes.Axes.set_xlabel(label, loc='None')

Let’s have a look at an example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax1= [0.2, 0.4, 0.6, 0.8, 1]y1= [0.3, 0.6, 0.8, 0.9, 1.5]# Add subplotsfig, ax = plt.subplots()# Add labels at x-axis at different locationsax.set_xlabel('X-Axis') # ORax.set_xlabel('X-Axis', loc='right') #ORax.set_xlabel('X-axis', loc='left')# Plot graphax.plot(x1, y1)# Display Graphplt.show()

We use the set_xlabel() method to add a label to the x-axis in the example above, and we pass loc as an argument and set its value to left and right.

Matplotlib X-axis Label - Python Guides (21)
Matplotlib X-axis Label - Python Guides (22)
Matplotlib X-axis Label - Python Guides (23)

Matplotlib x-axis label overlap

In this section, we’ll look at a situation where the x-axis labels start to overlap. As a result, we must format the x-axis to make the charts look neat.

Let’s have a look at the below example:

# Import Libraryimport matplotlib.pyplot as plt# Define Data x = ['I am the Label 1', "I am the Label 2", "I am the Label 3", "I am the Label 4", "I am the Label 5", "I am the Label 6"]y = [2, 4, 5, 6, 7.5, 3.8]# Plot chartplt.plot(x, y)# Display Chartplt.show()
Matplotlib X-axis Label - Python Guides (24)

In matplotlib, we have a method setp() that is used to set the rotation and alignment attributes of tick labels to avoid overlapping.

The setp() method has the following syntax:

matplotlib.pyplot.setp(object, **kwargs)

Let’s see an example where we remove overlapping:

# Import Libraryimport matplotlib.pyplot as plt# Define Data x = ['I am the Label 1', "I am the Label 2", "I am the Label 3", "I am the Label 4", "I am the Label 5", "I am the Label 6"]y = [2, 4, 5, 6, 7.5, 3.8]# Plot chartax= plt.subplot()plt.plot(x, y)# Function to avoid overlappingplt.setp(ax.get_xticklabels(), rotation=30, ha='right')# Display Chartplt.show()

To get ticklabels, we use the plt.setp() and get.xticklabels() functions, and we pass the rotation and ha arguments to the function, setting their values to 30 and right, respectively.

Matplotlib X-axis Label - Python Guides (25)

Read: Matplotlib savefig blank image

Matplotlib disable x-axis label

In this tutorial, we’ll look at how to remove labels from the x-axis in Matplotlib. By default, labels are displayed on the plot’s left and bottom axes in matplotlib.

We have to call the tick_params() method to remove the labels from the x-axis, or we can say from the bottom of the axes.

The syntax to disable labels from the x-axis is given below:

matplotlib.axes.Axes.tick_params(bottom=False, labelbottom=False)

bottom and labelbottom are both given the False boolean value. As a result, tick and tick labels are disabled from the x-axis. The x-axis label, however, remains.

Example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Create Figure and Axes fig,ax = plt.subplots()# Define Datax = np.arange(0, 30, 0.5)y = np.cos(x)# Make your plotax.plot(x, y)# Add labels ax.set_xlabel('X Label') ax.set_ylabel('Y Label') # Disabel X labelax.tick_params(bottom=False, labelbottom=False) # Show plt.show()
  • The plot() method is used to create a graph in the example above.
  • After that, we use the set_xlabel() and set_ylabel() methods to create labels on both axes.
  • We use the tick_params() method to remove the ticks and tick label from the plot’s x-axis. We pass the bottom and labelbottom arguments to the function and set their boolean values to False.
Matplotlib X-axis Label - Python Guides (26)

Read: Matplotlib bar chart labels

Matplotlib move x-axis label down

We’ll learn how to move the x-axis label and tick labels down the x-axis in this topic. We use the xlabel() function with the labelpad argument to move labels and the tick_params() method with the pad argument to move ticklabels.

To move downwards, we must pass a positive integer value; otherwise, it will start moving upwards.

The syntax is given below:

# To move labelsplt.xlabel(xlabel, labelpad=20) ORax.xaxis.labelpad=20# To move ticklabelsax.tick_params(pad=20)

Let’s see examples:

Example #1

# Import Libraryimport matplotlib.pyplot as plt# Add subplotsfig, ax = plt.subplots()# Define Datax= [0.2, 0.4, 0.6, 0.8, 1]y= [0.3, 0.6, 0.8, 0.9, 1.5]# Plot graphax.plot(x, y)# Add labels ax.set_xlabel('X Label') ax.set_ylabel('Y Label')# Move label downwardsax.xaxis.labelpad=30# Display Graphplt.show()

To move labels downwards in the example above, we use ax.xaxis.labelpad with a value of 30.

Matplotlib X-axis Label - Python Guides (27)

Example #2

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 30, 0.5)y = np.sin(x)# Plottingplt.plot(x, y)# Move label downwardsplt.xlabel('X-Axis', labelpad=30)# Visualizeplt.show()

We use the labelpad argument in the above example to move the label downwards and pass it to the xlabel() method. Its value has been set to 30.

Matplotlib X-axis Label - Python Guides (28)

Example #3

# Import Libraryimport matplotlib.pyplot as plt# Add subplotsfig, ax = plt.subplots()# Define Datax= [0, 1, 2, 3, 4]y= [2, 4, 6, 8, 10 ]# Plot graphplt.plot(x,y)# Add labels ax.set_xlabel('X Label') ax.set_ylabel('Y Label')# Move ticklabel downwardsax.tick_params(axis='x',pad=30)# Display Graphplt.show()

The tick_params() method is used to move tick labels downwards in the example above. We set the value of axis and pad to x and 30, respectively, as parameters.

Matplotlib X-axis Label - Python Guides (29)

Read: Add text to plot matplotlib in Python

READ: NumPy linspace in Python [7+ Examples]

Matplotlib x-axis label frequency

We’ll learn how to modify the tick frequency in matplotlib at both the figure and axis level in this user guide.

Figure-Level Tick Frequency

To adjust the figure level tick frequency, call the xticks() function and pass an array of ticks as a parameter. This array starts at 0 on the X-axis and ends at a maximum value of x, with ticks every 3 steps on the X-axis.

Example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.random.randint(low=0, high=30, size=15)y = np.random.randint(low=0, high=30, size=15)# Scatter Plotplt.scatter(x,y)# Tick frequencyplt.xticks(np.arange(0, max(x), 3))# Showplt.show()
Matplotlib X-axis Label - Python Guides (30)

Axis-Level Tick Frequency

We want to adjust the tick frequency on the axis level if we have multiple plots in a figure region. To adjust the tick frequency of the two axes separately, we use the set_xticks() function.

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Create figure and subplotfig = plt.figure(figsize=(12, 6))ax = fig.add_subplot(121)ax1 = fig.add_subplot(122)# Define Datax = np.random.randint(low=0, high=30, size=15)y = np.random.randint(low=0, high=30, size=15)# Scatter Plotax.scatter(x,y)ax1.scatter(x,y)# Tick Frequencyax.set_xticks(np.arange(0, max(x), 3))ax1.set_xticks(np.arange(0, max(y), 10))# Showplt.show()
  • We import matplotlib.pyplot and the numpy library in the example above.
  • Following that, we use the figure() and add_subplot() functions to build a figure and a subplot, respectively.
  • Then we use random to define data randint() is a method that returns a random number.
  • To create a scatter chart, use the scatter() method.
  • The set_xticks() method is used to control the frequency of ticks. This array starts at 0 and ends at the maximum value of x with a tick every 3 steps on subplot 1, while it starts at 0 and ends at the maximum value of x with a tick every 10 steps on subplot 2.
Matplotlib X-axis Label - Python Guides (31)

Read: Matplotlib plot error bars

Matplotlib x-axis label rotation

We learn how to rotate the x-axis label in matplotlib. We can position labels at any angle we choose.

The x-axis label can be rotated using a variety of functions:

  • By using plt.xticks()
  • By using ax.set_xticklabels()
  • By using ax.tick_params()

Matplotlib x axis label rotation by using plt.xticks()

To rotate the x-axis tick labels at 15 degrees, we use the plt.xticks() method with the rotation parameter in matplotlib.

Example:

# Import Libraryimport matplotlib.pyplot as plt# Define Datax= [0, 1, 2, 3, 4]y= [2, 4, 6, 8, 10 ]# Plot graphplt.plot(x,y)# Rotationplt.xticks(rotation=30)# Display Graphplt.show()
Matplotlib X-axis Label - Python Guides (32)

Matplotlib x-axis label rotation by using ax.set_xticklabels()

To rotate the x axis labels, we use the ax.set_xticklabels() method and pass rotation and label as parameters.

# Import Libraryimport matplotlib.pyplot as plt# Create subplotax = plt.subplot()# Define Datastudents = [6, 15, 8, 10]color = ["Red", "Black", "White", "Blue"]# Plot scatter chartplt.scatter(color, students, marker='*', color='g', s=50)# labelsplt.xlabel("Favourite color")plt.ylabel("No.of.students") # Rotationax.set_xticklabels(color, rotation=45)# Display chartplt.show()
Matplotlib X-axis Label - Python Guides (33)

Matplotlib x-axis label rotation by using ax.tick_params()

To rotate labels, we use the ax.tick_params() function, passing the axis and labelrotation as parameters and setting their values to x and 65 degrees, respectively.

Example:

# Import Libraryimport matplotlib.pyplot as plt# Create subplotax = plt.subplot()# Define Datastudents = [6, 15, 8, 10]color = ["Red", "Black", "White", "Blue"]# Plot scatter chartplt.scatter(color, students, marker='*', color='g', s=50)# labelsplt.xlabel("Favourite color")plt.ylabel("No.of.students") # Rotationax.tick_params(axis='x', labelrotation=180)# Display chartplt.show()
Matplotlib X-axis Label - Python Guides (34)

Read: Matplotlib remove tick labels

Matplotlib x-axis label orientation

The x axis label orientation is discussed in this section. The orientation option allows you to rotate the x-axis label at whatever angle you like. The rotation argument is passed to the plt.xlabel() method to rotate labels.

Example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.random.randint(low=0, high=30, size=15)y = np.random.randint(low=0, high=30, size=15)# Scatter Plotplt.scatter(x,y)# Rotateplt.xlabel('X-Axis', rotation=65, size=20)# Showplt.show()
  • In the above example, we use the random.randint() method to define data and the scatter() method to plot it in a scatter graph.
  • plt.xlabel() method is used to add a label or we can say descriptive label to the x-axis, and the rotation argument is passed to the method to adjust the x-axis label’s orientation.
Matplotlib X-axis Label - Python Guides (35)

Read: Matplotlib rotate tick labels

Matplotlib rotate x-axis label subplot

If we have multiple subplots, we will explore how to rotate the x-axis label of the specific subplot.

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as plt# 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]x3= [5, 8, 12]y3= [3, 6, 9]x4= [7, 8, 15]y4= [6, 12, 18]# Add subplotsfig, ax = plt.subplots(2, 2)# Plot graphax[0, 0].plot(x1, y1)ax[0, 1].plot(x2, y2)ax[1, 0].plot(x3, y3)ax[1, 1].plot(x4, y4)# Add labels at x-axisax[0, 0].set_xlabel('Subplot 1', rotation=15)ax[0, 1].set_xlabel('Subplot 2')ax[1, 0].set_xlabel('Subplot 3')ax[1, 1].set_xlabel('Subplot 4')# Rotate x ticksax[1, 1].set_xticklabels(ax[1, 1].get_xticks(), rotation=45)# Display Graphfig.tight_layout()plt.show()
  • To rotate the x-axis label, we use the set_xlabel() method and pass the arguments xlabel and rotation to the function.
  • The set_xticklabels() function is also used to rotate the tick labels on the x-axis. We use the get_xticks() method to get the ticks on the x-axis, as well as the rotation argument to rotate the ticklabels.
Matplotlib X-axis Label - Python Guides (36)

Matplotlib replace x-axis label

We’ll learn how to change the default x-axis tick label to a label of our own in this tutorial.

Example:

We’ll replace a specific xticklabel with the label of our choice in this example. We do this by calling the set_xticklabels() method and passing the new tick label to it.

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Create subplotfig, ax = plt.subplots()fig.canvas.draw()# Define Datax = np.random.randint(low=0, high=30, size=15)y = np.random.randint(low=0, high=30, size=15)# Scatter Plotplt.scatter(x,y)# Replace labels[2] = 'Change'ax.set_xticklabels(labels)# Showplt.show()
  • In the example above, we use the random.randint() function to define data and the scatter() method to plot a graph between them.
  • The set_xticklabels() method is then used to replace the specific label.
Matplotlib X-axis Label - Python Guides (37)

Read: Put legend outside plot matplotlib

Matplotlib reduce x-axis label

To decrease the number of xticks on the axis, use the locator_params() method in matplotlib.

The following is the syntax:

matplotlib.pyplot.locator_params(axis=, nbins=)

The following are the parameters that were used:

  • axis: specify whether x-axis or y-axis.
  • nbins: specify the number of ticks.

Let’s see an example:

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 40, 0.5)y = np.tan(x)# Plottingplt.plot(x, y)# Add x-axis labelplt.xlabel('X-Axis')plt.ylabel('Y-Axis')# Reduce xtick labelplt.locator_params(axis="x", nbins=5)# Visualizeplt.show()
  • We import matplotlib.pyplot and the numpy library in the example above.
  • After that, we use the arange() and tan() functions to define data.
  • To plot a graph between x and y data coordinates, use the plt.plot() method.
  • The xlabel() and ylabel() functions are used to add labels to the axes.
  • To decrease x-axis labels, use the plt.locator_params() method. We set the values of axis and nbins to x and 5, respectively, as parameters.
Matplotlib X-axis Label - Python Guides (38)
Matplotlib X-axis Label - Python Guides (39)

Also, take a look at some more tutorials on Matplotlib.

  • Matplotlib Pie Chart Tutorial
  • Matplotlib secondary y-axis

So, in this Python tutorial, we have discussed the“Matplotlib x axis label”and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib x-axis label
  • Matplotlib x-axis label example
  • Matplotlib x-axis label size
  • Matplotlib x-axis label color
  • Matplotlib x-axis label vertical
  • Matplotlib x-axis label date
  • Matplotlib x-axis label spacing
  • Matplotlib x-axis label bold
  • Matplotlib x-axis label range
  • Matplotlib x-axis label remove
  • Matplotlib x-axis label scientific notation
  • Matplotlib x-axis tick label
  • Matplotlib x-axis label string
  • Matplotlib x-axis tick label size
  • Matplotlib x-axis tick label color
  • Matplotlib x-axis label subplot
  • Matplotlib x-axis label on top
  • Matplotlib x-axis label position
  • Matplotlib x-axis label overlap
  • Matplotlib disable x-axis label
  • Matplotlib move x-axis label down
  • Matplotlib x-axis label frequency
  • Matplotlib x-axis label rotation
  • Matplotlib x-axis label orientation
  • Matplotlib rotate x-axis label subplot
  • Matplotlib replace x-axis label
  • Matplotlib reduce x-axis label

Matplotlib X-axis Label - Python Guides (40)

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.

Matplotlib X-axis Label - Python Guides (2024)

References

Top Articles
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6043

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.