Matplotlib x-axis label

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

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 Library

import matplotlib.pyplot as plt

# Define Data

x = [0, 1, 2, 3, 4]
y = [2, 4, 6, 8, 12]

# Plotting

plt.plot(x, y)

# Add x-axis label

plt.xlabel('X-axis Label')

# Visualize

plt.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 example
plt.xlabel()

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 Library

import matplotlib.pyplot as plt

# Define Data

x = [0, 1, 2, 3, 4]
y = [2, 10, 6, 5, 12]

# Plotting

plt.plot(x, y, '--')

# Add x-axis label

plt.xlabel('X-axis Label', fontsize=20)

# Visualize

plt.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 size
plt.xlabel(fontsize=20)

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 Library

import matplotlib.pyplot as plt

# Define Data

x = [0, 1, 2, 3, 4]
y = [2, 10, 6, 5, 12]

# Plotting

plt.plot(x, y, '--')

# Add x-axis label

plt.xlabel('X-axis Label', fontsize=15, color='r')

# Visualize

plt.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 color
plt.xlabel(color=None)

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 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.plot(x, y, '--')

# Add x-axis label

plt.xlabel('Time', size = 15, rotation='vertical')

# Visualize

plt.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 vertical
plt.xlabel(rotation=’vertical’)

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 Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

# Define Data

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3]

# Plotting

plt.plot_date(dates, y)

# Avoid overlapping

plt.gcf().autofmt_xdate()

# Visualize

plt.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 overlapping
autofmt_xdate()

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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 30, 0.5)
y = np.cos(x)

# Plotting

plt.plot(x, y, '--')

# Label spacing

plt.xlabel('X-Axis')

                   # OR


plt.xlabel('X-Axis', labelpad=30)

                   # OR


plt.xlabel('X-Axis', labelpad=60)

# Visualize

plt.show()

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

matplotlib x axis label spacing
plt.xlabel(xlabel)
matplotlib x axis label set spacing
plt.xlabel(xlabel, labelpad=30)
matplotlib x axis label adjust spacing
plt.xlabel(xlabel, labelpad=60)

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 Library

import matplotlib.pyplot as plt

# Define Data

x = [0, 1, 2, 3, 4]
y = [2, 10, 6, 9, 8.5]

# Plotting

plt.plot(x, y, '--')

# Bold x-axis label

plt.xlabel('X-Axis Label', fontweight='bold')

# Visualize

plt.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 bold
plt.xlabel(fontweight=’bold’)

Read: Matplotlib subplot tutorial

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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 30, 0.5)
y = np.cos(x)

# Plotting

plt.plot(x, y)

# Add x-axis label

plt.xlabel('X-Axis')

# x-axis limit

plt.xlim(-2.5, 6)

# Display

plt.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 range
Normal x-axis
matplotlib x axis label set range
plt.xlim()

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 Library

import matplotlib.pyplot as plt

# Create Figure and Axes 

fig,ax = plt.subplots(1)

# Define Data

x = np.arange(0, 30, 0.5)
y = np.cos(x)

# Make your plot

ax.plot(x, y)

# Add labels
        
ax.set_xlabel('X Label')        
ax.set_ylabel('Y Label')
        
# Remove X label

plt.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 remove
” Remove x-axis labels “

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 Library

import matplotlib.pyplot as plt

# Define Data

x = [1000, 2000, 3000]
y = [3000, 4000, 5000]

# Plot

plt.plot(x, y)

# Scientific Notation

plt.ticklabel_format(axis="x", style="sci", scilimits=(0,0))

# Display

plt.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 scientific notation
” Scientific Notation X-axis “

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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define data

x = [1, 2, 3, 4, 5]
y = [2.5, 0.6, 4.9, 3, 6]

# Create subplot

ax = plt.subplot()

# Define tick label

ax.set_xticklabels([2, 4, 6, 8, 10])

# Display graph

plt.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 tick label
” By default x-axis tick labels “

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

matplotlib x axis set tick label
set_ticklabels()

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 Library

import matplotlib.pyplot as plt

# Define Data

programmers = [5, 6, 2, 3]
languages = ["Python", "Java", "C++", "C" ]

# Plot chart

plt.plot( languages, programmers, color= 'r', marker= 'o')

# Display chart

plt.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 string
“String Labels”

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 Library

import matplotlib.pyplot as plt

# Define Data

students = [6, 15, 8, 10]
color = ["Red", "Black", "White", "Blue"]

# Plot sactter chart

plt.scatter(color, students, marker='*', color='g', s=50)

# Fontsize of tick labels

plt.xticks(fontsize=15)

# Labels

plt.xlabel("Favourite color")
plt.ylabel("No.of.students")    

# Display chart

plt.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 tick label size
plt.xticks(fontsize=15)

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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 30, 0.5)
y = np.tan(x)

# Plotting

plt.plot(x, y)

# Change color of xticks

plt.xticks(color='r')

# Visualize

plt.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 tick label color
plt.xticks(color=’red’)

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 Library

import matplotlib.pyplot as plt

# 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]

x3= [5, 8, 12]
y3= [3, 6, 9]

x4= [7, 8, 15]
y4= [6, 12, 18]

# Add subplots

fig, ax = plt.subplots(2, 2)

# Add labels at x-axis

ax[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 graph

ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

# Display Graph

fig.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 subplot
set_xlabel()

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.

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 Marker
matplotlib.axes.Axes.tick_params(bottom=True, top=False, left=True, right=False)

# Tick Label
matplotlib.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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 30, 0.2)
y = np.tan(x)

# Add subplot

ax = plt.subplot()

# Plotting

plt.plot(x, y)

# Xlabel on top

ax.tick_params(top=True, bottom=False)
ax.tick_params(labeltop=True, labelbottom=False)

# Visualize

plt.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 on top
ax.tick_params()

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 Library

import matplotlib.pyplot as plt

# Define Data

x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]

# Add subplots

fig, ax = plt.subplots()

# Add labels at x-axis at different locations

ax.set_xlabel('X-Axis')

                # OR


ax.set_xlabel('X-Axis', loc='right')

                #OR

ax.set_xlabel('X-axis', loc='left')

# Plot graph

ax.plot(x1, y1)

# Display Graph

plt.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 position
By default loc=’center’
matplotlib x axis label right position
loc=’right’
matplotlib x axis label left position
loc=’left’

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 Library

import 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 chart

plt.plot(x, y)

# Display Chart

plt.show()
matplotlib x axis label overlap
“X-axis Label Overlap Each Other”

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 Library

import 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 chart

ax= plt.subplot()
plt.plot(x, y)

# Function to avoid overlapping

plt.setp(ax.get_xticklabels(), rotation=30, ha='right')

# Display Chart

plt.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 avoid overlap
“X-axis Without Overlapping”

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 Library


import matplotlib.pyplot as plt
import numpy as np

# Create Figure and Axes 


fig,ax = plt.subplots()

# Define Data


x = np.arange(0, 30, 0.5)
y = np.cos(x)

# Make your plot


ax.plot(x, y)

# Add labels
        
ax.set_xlabel('X Label')        
ax.set_ylabel('Y Label')
       
# Disabel X label


ax.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 disable x axis
tick_params(bottom=False, labelbottom=False)

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 labels

plt.xlabel(xlabel, labelpad=20)
            OR
ax.xaxis.labelpad=20

# To move ticklabels

ax.tick_params(pad=20)

Let’s see examples:

Example #1

# Import Library


import matplotlib.pyplot as plt

# Add subplots


fig, ax = plt.subplots()

# Define Data


x= [0.2, 0.4, 0.6, 0.8, 1]
y= [0.3, 0.6, 0.8, 0.9, 1.5]

# Plot graph


ax.plot(x, y)

# Add labels
        
ax.set_xlabel('X Label')        
ax.set_ylabel('Y Label')

# Move label downwards


ax.xaxis.labelpad=30

# Display Graph


plt.show()

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

matplotlib move x axis label down
labelpad=30

Example #2

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 30, 0.5)
y = np.sin(x)

# Plotting

plt.plot(x, y)

# Move label downwards

plt.xlabel('X-Axis', labelpad=30)

# Visualize

plt.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 move x axis label downwards
labelpad=30

Example #3

# Import Library

import matplotlib.pyplot as plt

# Add subplots


fig, ax = plt.subplots()

# Define Data

x= [0, 1, 2, 3, 4]
y= [2, 4, 6, 8, 10 ]

# Plot graph

plt.plot(x,y)

# Add labels
        
ax.set_xlabel('X Label')        
ax.set_ylabel('Y Label')

# Move ticklabel downwards

ax.tick_params(axis='x',pad=30)

# Display Graph


plt.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 move x axis tick label down
tick_params(axis=x, pad=30)

Read: Add text to plot matplotlib in Python

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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.random.randint(low=0, high=30, size=15)
y = np.random.randint(low=0, high=30, size=15)

# Scatter Plot


plt.scatter(x,y)

# Tick frequency


plt.xticks(np.arange(0, max(x), 3))

# Show

plt.show()
matplotlib x axis label frequency
“X-axis Tick Frequency”

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 Library


import matplotlib.pyplot as plt
import numpy as np

# Create figure and subplot


fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(121)
ax1 = fig.add_subplot(122)

# Define Data


x = np.random.randint(low=0, high=30, size=15)
y = np.random.randint(low=0, high=30, size=15)

# Scatter Plot


ax.scatter(x,y)
ax1.scatter(x,y)

# Tick Frequency


ax.set_xticks(np.arange(0, max(x), 3))
ax1.set_xticks(np.arange(0, max(y), 10))

# Show


plt.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 set frequency
set_xticks()

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 Library

import matplotlib.pyplot as plt

# Define Data

x= [0, 1, 2, 3, 4]
y= [2, 4, 6, 8, 10 ]

# Plot graph

plt.plot(x,y)

# Rotation

plt.xticks(rotation=30)

# Display Graph

plt.show()
matplotlib x axis label rotation
plt.xticks(rotation=30)

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 Library

import matplotlib.pyplot as plt

# Create subplot

ax = plt.subplot()

# Define Data

students = [6, 15, 8, 10]
color = ["Red", "Black", "White", "Blue"]

# Plot scatter chart

plt.scatter(color, students, marker='*', color='g', s=50)

# labels

plt.xlabel("Favourite color")
plt.ylabel("No.of.students") 

# Rotation


ax.set_xticklabels(color, rotation=45)

# Display chart

plt.show()
matplotlib x axis label change rotation
ax.set_xticklabels(color, rotation=45)

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 Library

import matplotlib.pyplot as plt

# Create subplot

ax = plt.subplot()

# Define Data

students = [6, 15, 8, 10]
color = ["Red", "Black", "White", "Blue"]

# Plot scatter chart


plt.scatter(color, students, marker='*', color='g', s=50)

# labels

plt.xlabel("Favourite color")
plt.ylabel("No.of.students") 

# Rotation

ax.tick_params(axis='x', labelrotation=180)

# Display chart


plt.show()
matplotilb rotate x axis label
ax.tick_params(axis=’x’, labelrotation=180)

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 Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.random.randint(low=0, high=30, size=15)
y = np.random.randint(low=0, high=30, size=15)

# Scatter Plot

plt.scatter(x,y)

# Rotate

plt.xlabel('X-Axis', rotation=65, size=20)

# Show

plt.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 orientation
“X Label at 65 Degrees”

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 Library

import matplotlib.pyplot as plt

# 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]

x3= [5, 8, 12]
y3= [3, 6, 9]

x4= [7, 8, 15]
y4= [6, 12, 18]

# Add subplots

fig, ax = plt.subplots(2, 2)

# Plot graph

ax[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-axis

ax[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 ticks

ax[1, 1].set_xticklabels(ax[1, 1].get_xticks(), rotation=45)

# Display Graph

fig.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 rotate x axis label subplot
” Rotation of labels and tick labels “

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 Library


import matplotlib.pyplot as plt
import numpy as np

# Create subplot


fig, ax = plt.subplots()
fig.canvas.draw()

# Define Data


x = np.random.randint(low=0, high=30, size=15)
y = np.random.randint(low=0, high=30, size=15)

# Scatter Plot


plt.scatter(x,y)


# Replace 


labels[2] = 'Change'
ax.set_xticklabels(labels)

# Show


plt.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 replace
” Replace x-axis tick labels “

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 Library


import matplotlib.pyplot as plt
import numpy as np

# Define Data


x = np.arange(0, 40, 0.5)
y = np.tan(x)

# Plotting


plt.plot(x, y)

# Add x-axis label


plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Reduce xtick label


plt.locator_params(axis="x", nbins=5)

# Visualize


plt.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 reduce labels at x axis
” Default number of xticks “
matplotlib reduce x axis label
” Reduce the number of xticks “

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