15.1 C
London
Friday, July 5, 2024
HomePythonData Visualizations in PythonHow to Create a Log-Log Plot in Python

How to Create a Log-Log Plot in Python

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Additional Resources

How to Create a Log-Log Plot in R
How to Create a Log-Log Plot in Excel

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories