How to Create a Log-Log Plot in Python?


A log-log plot is a plot that uses logarithmic scales on both the x-axis and the y-axis.

This type of plot is useful for visualizing two variables when the true relationship between them follows some type of power law.

This tutorial explains how to create a log-log plot in Python.

How to Create a Log-Log Plot in Python

Suppose we have the following pandas DataFrame:

import pandas as pd
import matplotlib.pyplot as plt

#create DataFrame
df = pd.DataFrame({'x': [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
                         14, 15, 16, 17, 18, 19, 20, 21, 22],
                   'y': [3, 4, 5, 7, 9, 13, 15, 19, 23, 24, 29,
                         38, 40, 50, 56, 59, 70, 89, 104, 130]})

#create scatterplot
plt.scatter(df.x, df.y)

Clearly the relationship between x and y follows a power law.

The following code shows how to use numpy.log() to perform a log transformation on both variables and create a log-log plot to visualize the relationship bewteen them:

import numpy as np

#perform log transformation on both x and y
xlog = np.log(df.x)
ylog = np.log(df.y)

#create log-log plot
plt.scatter(xlog, ylog)

The x-axis displays the log of x and the y-axis displays the log of y.

Notice how the relationship between log(x) and log(y) is much more linear compared to the previous plot.

Feel free to add a title and axis labels to make the plot easier to interpret:

#create log-log plot with labels
plt.scatter(xlog, ylog, color='purple')
plt.xlabel('Log(x)')
plt.ylabel('Log(y)')
plt.title('Log-Log Plot')

Also note that you can create a line plot instead of a scatterplot by simply using plt.plot() as follows:

#create log-log line plot
plt.plot(xlog, ylog, color='purple')
plt.xlabel('Log(x)')
plt.ylabel('Log(y)')
plt.title('Log-Log Plot')

Log-log plot in Python

x