Change Marker Size in 3D Scatter Plot using Matplotlib

Recently, I was working on a data visualization project that required representing customer data from different U.S. states in a 3D scatter plot. I wanted to make the visualization more meaningful by adjusting the marker sizes based on sales volume. That’s when I realized, many people don’t know how to effectively control marker size in a 3D scatter plot using Python’s Matplotlib.

In this tutorial, I’ll walk you through everything I’ve learned about customizing 3D scatter marker sizes in Matplotlib. I’ll show you multiple methods, explain how marker size works in 3D plots, and share some practical examples you can use right away.

What is a 3D Scatter Plot in Python Matplotlib?

A 3D scatter plot is a type of plot that displays data points in three dimensions, X, Y, and Z. It’s perfect for visualizing relationships among three variables at once.

In Python Matplotlib, we can create 3D scatter plots using the Axes3D module from mpl_toolkits.mplot3d. It allows you to visualize data in space and customize aspects like color, marker type, and size.

When I first started using 3D scatter plots in Matplotlib, I noticed that the marker size parameter (s) behaves slightly differently compared to 2D plots. So, understanding how to control it properly is key to creating clear and effective visualizations.

Adjust Marker Size in a 3D Scatter Plot

Changing the marker size in a 3D scatter plot is not just about aesthetics; it’s about communication.

For instance, if you’re analyzing sales data across different U.S. states, you can make the marker size represent total revenue. Larger markers can indicate higher sales, while smaller ones can represent lower sales. This simple adjustment can make your visualization more intuitive and informative.

Get Started with Python Matplotlib 3D Scatter Plot

Before we begin, make sure you have Matplotlib installed. If not, you can install it using pip:

pip install matplotlib

Once installed, you can start by importing the necessary libraries and creating a basic 3D scatter plot.

Example 1: Vary Marker Size Based on Data Values

Sometimes, you want the marker size to represent a variable, like population, revenue, or temperature.

To achieve this, we can pass an array of values to the s parameter.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Generate synthetic data
np.random.seed(10)
x = np.random.randint(10, 100, 30)
y = np.random.randint(10, 100, 30)
z = np.random.randint(10, 100, 30)

# Marker size based on z-values (for example, revenue)
marker_size = z * 5  # Scale it up for better visibility

fig = plt.figure(figsize=(9, 7))
ax = fig.add_subplot(111, projection='3d')

# Create scatter plot with variable marker size
sc = ax.scatter(x, y, z, c=z, cmap='viridis', s=marker_size, alpha=0.8)

ax.set_xlabel('Marketing Spend ($)')
ax.set_ylabel('Customer Reach')
ax.set_zlabel('Revenue ($)')
plt.title('3D Scatter Plot with Variable Marker Size in Python Matplotlib')

# Add color bar
plt.colorbar(sc, ax=ax, label='Revenue Level')

plt.show()

I executed the above example code and added the screenshot below.

Change Marker Size in 3D Scatter Plot Matplotlib

In this example, marker size is directly linked to the z values. Larger z values produce larger markers, making it easy to spot high performers visually.

Example 2: Use a Custom Function for Marker Size

Sometimes, the relationship between marker size and your data isn’t linear. For instance, you might want to apply a logarithmic or exponential scale to make the visualization more balanced.

Here’s how you can use a custom function for marker size in Python Matplotlib 3D scatter plots.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Generate data
np.random.seed(7)
x = np.random.randint(50, 500, 25)
y = np.random.randint(50, 500, 25)
z = np.random.randint(50, 500, 25)

# Apply logarithmic scaling for marker size
marker_size = np.log(z) * 30

fig = plt.figure(figsize=(9, 7))
ax = fig.add_subplot(111, projection='3d')

# Create 3D scatter plot with custom marker size
sc = ax.scatter(x, y, z, c=z, cmap='coolwarm', s=marker_size, edgecolors='k', alpha=0.9)

ax.set_xlabel('Store Size (sq ft)')
ax.set_ylabel('Monthly Visitors')
ax.set_zlabel('Sales Volume ($)')
plt.title('3D Scatter Plot with Logarithmic Marker Size in Python Matplotlib')

plt.colorbar(sc, ax=ax, label='Sales Volume')
plt.show()

I executed the above example code and added the screenshot below.

Change Marker Size in Matplotlib 3D Scatter Plot

Here, I used a logarithmic transformation to adjust the marker size distribution. This technique works great when your data varies widely in scale.

Example 3: Add Legends for Marker Size

A common question I get is: How can I add a legend that explains what marker sizes represent?

While Matplotlib doesn’t automatically create a legend for marker sizes, we can manually add one using Line2D.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
import numpy as np

# Sample data
np.random.seed(5)
x = np.random.randint(1, 100, 15)
y = np.random.randint(1, 100, 15)
z = np.random.randint(1, 100, 15)
sizes = z * 10

fig = plt.figure(figsize=(9, 7))
ax = fig.add_subplot(111, projection='3d')

# Create scatter plot
sc = ax.scatter(x, y, z, c=z, cmap='plasma', s=sizes, alpha=0.8)

# Create custom legend
legend_elements = [
    Line2D([0], [0], marker='o', color='w', label='Low Sales', markerfacecolor='gray', markersize=5),
    Line2D([0], [0], marker='o', color='w', label='Medium Sales', markerfacecolor='gray', markersize=10),
    Line2D([0], [0], marker='o', color='w', label='High Sales', markerfacecolor='gray', markersize=15)
]

ax.legend(handles=legend_elements, title='Sales Level')
ax.set_xlabel('Advertising Spend ($)')
ax.set_ylabel('Customer Engagement')
ax.set_zlabel('Sales ($)')
plt.title('3D Scatter Plot with Marker Size Legend in Python Matplotlib')

plt.show()

I executed the above example code and added the screenshot below.

Matplotlib Change Marker Size in 3D Scatter Plot

This approach adds clarity to your visualization, especially when presenting data to non-technical audiences.

Example 4: Combine Color and Marker Size for Better Insights

One of my favorite techniques is combining both color and marker size to represent two different variables.

Let’s say you want to show both revenue and customer satisfaction in one 3D plot.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Generate data
np.random.seed(20)
x = np.random.randint(1, 50, 25)
y = np.random.randint(1, 50, 25)
z = np.random.randint(1, 50, 25)
revenue = np.random.randint(100, 1000, 25)
satisfaction = np.random.rand(25)

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Combine color and size
sc = ax.scatter(x, y, z, c=satisfaction, cmap='viridis', s=revenue/5, alpha=0.8, edgecolors='k')

ax.set_xlabel('Region Index')
ax.set_ylabel('Product Category')
ax.set_zlabel('Quarterly Sales ($)')
plt.title('3D Scatter Plot with Color and Marker Size in Python Matplotlib')

plt.colorbar(sc, ax=ax, label='Customer Satisfaction')
plt.show()

I executed the above example code and added the screenshot below.

Change Marker Size in 3D Scatter Plot using Matplotlib

This visualization gives you a multidimensional view of your data, helping you identify correlations and trends easily.

Tips for Choosing the Right Marker Size in Matplotlib 3D Scatter Plots

Here are some quick tips I’ve learned from experience:

  • Always scale marker sizes carefully; too large and they overlap, too small and they’re invisible.
  • Use transparency (alpha) to make overlapping markers visible.
  • When presenting data, always include a legend or color bar for context.
  • Normalize your data before mapping it to marker sizes for consistent scaling.

These small adjustments can make your Python Matplotlib 3D scatter plots look professional and easy to understand.

Conclusion

So that’s how you can control and customize marker size in a 3D scatter plot using Python Matplotlib. We explored different ways, from simple fixed sizes to dynamic, data-driven scaling. We also looked at how to add legends and combine marker size with color for richer insights.

When I first started with data visualization, I underestimated how much impact marker size could have. But with the right approach, you can turn a plain 3D scatter plot into a powerful storytelling tool.

You may also like to read:

Leave a Comment

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.