Plot logarithmic axes with matplotlib in Python

In this post, we will discuss how to plot logarithmic axes with matplotlib in Python. Matplotlib is a popular tool for data visualization in Python because of its versatility. Here, we will see how to plot a logarithmic graph using matplotlib.

If you’re reading this article, it’s a good assumption that you already have matplotlib installed. However, a short description of the installation is provided. Feel free to skip it if you have already installed matplotlib.

Note that matplotlib is a large library, but one single command will suffice the installation of the library. Run the following command on your command prompt. Everything that’s required should automatically be installed.

pip3 install matplotlib

Check if the library was installed correctly by importing matplotlib on your Python shell.

Python program to plot logarithmic axes using matplotlib

The process to plot logarithmic axes is extremely similar to regular plotting except for one line of code which is specifying the type of axes as ‘log’.

For demonstrating this, we will plot the powers of 10 against their exponents. With a basic understanding of logarithms, you’ll know that this will be a linear logarithmic graph.

First, we will set up the subplot required to plot the graph.

from matplotlib import pyplot

# Create a subplot to show the graph
pyplot.subplot(1, 1, 1)          

We have our subplot ready and now it’s time to plot the graph and set the axis type as ‘log’.

# Powers of 10
a = [10**i for i in range(10)]

# Plotting the graph
pyplot.plot(a, color='blue', lw=2)

# Setting a logarithmic scale for y-axis

That’s all that needs to be done to plot a graph with a logarithmic scale. Without the logarithmic scale, the data that we plotted would show a curve with an exponential rise. The graph will be linear with a logarithmic y-axis.

plot logarithmic axes with matplotlib

Similarly, you can apply the same for x-axis by using pyplot.xscale(‘log’). Some of the other scales that can be used are ‘linear’, ‘symlog’, ‘logit’. You can refer to the official documentation for it here. I hope you found this article helpful.

See also:

Leave a Reply

Your email address will not be published. Required fields are marked *