Log-Log Plots in Matplotlib

When I first started working with data visualization in Python, I quickly realized that plotting data on a logarithmic scale is essential for many real-world datasets. Log-log plots, where both the x-axis and y-axis are on a logarithmic scale, are particularly useful for visualizing relationships that span several orders of magnitude.

In this guide, I will walk you through how to create log-log plots using Matplotlib, the go-to plotting library in Python. I’ll share practical methods I’ve used over the years, making it easier for you to apply these techniques to your projects.

Let’s start!

What is a Log-Log Plot?

A log-log plot is a graph that uses logarithmic scales on both axes. This means that instead of plotting raw values, the plot displays the logarithm of the values. This is particularly helpful when your data covers a wide range of values, for example, plotting city populations across the US or the frequency of earthquakes by magnitude.

Using logarithmic scales can help linearize certain types of relationships, such as power laws, making trends easier to spot and analyze.

When Should You Use a Log-Log Plot?

I find log-log plots especially useful when:

  • Your data spans multiple orders of magnitude.
  • You want to identify power-law relationships.
  • You need to emphasize relative changes rather than absolute differences.

For example, if you’re analyzing the distribution of income across different states or the growth of tech startups in Silicon Valley, a log-log plot can make the trends clearer.

Read Matplotlib Update Plot in Loop

Create a Basic Log-Log Plot in Matplotlib

Let me show you the simplest way to create a log-log plot using Matplotlib.

import matplotlib.pyplot as plt
import numpy as np

# Sample data: US city populations (fictional example)
city_population = np.array([1e4, 5e4, 2e5, 1e6, 5e6, 1e7])
city_rank = np.array([6, 5, 4, 3, 2, 1])

plt.loglog(city_rank, city_population, marker='o')
plt.xlabel('City Rank (log scale)')
plt.ylabel('Population (log scale)')
plt.title('Log-Log Plot of US City Populations')
plt.grid(True, which="both", ls="--")
plt.show()

I executed the above example code and added the screenshot below

plt.loglog

In this example, both axes are set to logarithmic scale using plt.loglog(). The marker='o' helps visualize individual data points.

Check out the Matplotlib Pie Chart Tutorial

Method 1: Use plt.loglog() Function

The easy way to create a log-log plot is by using Matplotlib’s built-in loglog() function. This function automatically sets both x and y axes to logarithmic scales.

It’s quick and requires minimal code. Great for exploratory data analysis when you want to visualize data quickly.

Example:

plt.loglog(x_data, y_data)

You can customize markers, colors, and line styles as usual.

Method 2: Set Axes Scales Manually

Sometimes, you want more control over your plot, especially if you’re combining multiple plots or customizing axes independently.

Here’s how I manually set the axes scales:

fig, ax = plt.subplots()
ax.plot(x_data, y_data, marker='x', linestyle='--')
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('X-axis (log scale)')
ax.set_ylabel('Y-axis (log scale)')
ax.set_title('Manual Log-Log Plot')
ax.grid(True, which='both', linestyle=':')
plt.show()

I executed the above example code and added the screenshot below

matplotlib log scale

This method is useful when you want to mix different scale types on your axes or combine log-log plots with other plot types.

Read Matplotlib Scatter Plot Color

Handle Zero or Negative Values

One challenge I often encounter is that log scales cannot display zero or negative values. If your dataset contains these, you need to filter or transform them before plotting.

For example:

import numpy as np

# Filter out non-positive values
x_filtered = x_data[x_data > 0]
y_filtered = y_data[y_data > 0]

plt.loglog(x_filtered, y_filtered, marker='s')
plt.show()

I executed the above example code and added the screenshot below

python log scale

Alternatively, you could add a small constant to shift values, but be cautious as it may affect data interpretation.

Customize Your Log-Log Plot

To make your plots more insightful and visually appealing, I recommend:

  • Adding grid lines with ax.grid(True, which='both') to help read values.
  • Label axes clearly, specifying the log scale.
  • Using markers to highlight data points.
  • Adding a legend if you plot multiple datasets.
  • Adjusting ticks to meaningful intervals using ax.set_xticks() and ax.set_yticks() if needed.

Check out Matplotlib Plot NumPy Array

Real-World Example: Tech Startup Growth in the US

Imagine you have data on the number of users (in thousands) and revenue (in millions) for tech startups in Silicon Valley. Both metrics vary widely, so a log-log plot helps visualize the relationship.

users = np.array([1, 10, 50, 200, 500, 1000])  # in thousands
revenue = np.array([0.1, 1, 5, 20, 50, 120])  # in millions

plt.loglog(users, revenue, marker='^', color='green')
plt.xlabel('Users (Thousands, log scale)')
plt.ylabel('Revenue (Millions, log scale)')
plt.title('Tech Startup Growth in Silicon Valley')
plt.grid(True, which='both', linestyle='--')
plt.show()

This plot quickly shows how revenue scales with user base across startups of different sizes.

Mastering log-log plots with Matplotlib has been a game-changer in my data analysis toolkit. Whether you’re working with financial data, scientific measurements, or tech metrics, these plots can reveal insights hidden in complex datasets.

The methods I shared here are simple to implement and adaptable to your specific needs. Start experimenting with your US-based datasets today and see how log-log plots can transform your data storytelling.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.