How to Fix Missing 3D Plots in Python Logistic Regression Visualizations

This guide shows why a Python Matplotlib 3D plot of a logistic‑regression loss surface may fail, provides a complete code example, explains version‑specific issues, and demonstrates a working solution that renders both 2D and 3D visualizations correctly.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Fix Missing 3D Plots in Python Logistic Regression Visualizations

1. Introduction

I'm a Python enthusiast. Recently a member asked why a 3‑D plot generated with Matplotlib does not appear. Below is the original code that attempts to plot a logistic‑regression loss surface.

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load data
data = load_breast_cancer()
X, y = data['data'][:, :2], data['target']

# Fit logistic regression without intercept
lr = LogisticRegression(fit_intercept=False)
lr.fit(X, y)
theta1 = lr.coef_[0, 0]
theta2 = lr.coef_[0, 1]
print(theta1)
print(theta2)

def p_theta_function(features, w1, w2):
    """Compute the predicted probability given w1 and w2."""
    z = w1 * features[0] + w2 * features[1]
    return 1 / (1 + np.exp(-z))

def loss_function(sample_features, sample_labels, w1, w2):
    """Calculate the total loss for a set of samples."""
    result = 0
    for feature, label in zip(sample_features, sample_labels):
        p = p_theta_function(feature, w1, w2)
        loss = -label * np.log(p) - (1 - label) * np.log(1 - p)
        result += loss
    return result

theta1_space = np.linspace(theta1-0.6, theta1+0.6, 50)
theta2_space = np.linspace(theta2-0.6, theta2+0.6, 50)
result1 = np.array([loss_function(X, y, i, theta2) for i in theta1_space])
result2 = np.array([loss_function(X, y, theta1, i) for i in theta2_space])

fig1 = plt.figure(figsize=(8, 6))
plt.subplot(221)
plt.plot(theta1_space, result1)

plt.subplot(222)
plt.plot(theta2_space, result2)

plt.subplot(223)
theta1_grid, theta2_grid = np.meshgrid(theta1_space, theta2_space)
loss_grid = loss_function(X, y, theta1_grid, theta2_grid)
plt.contour(theta1_grid, theta2_grid, loss_grid)

plt.subplot(224)
plt.contour(theta1_grid, theta2_grid, loss_grid, 30)

fig2 = plt.figure()
ax = Axes3D(fig2)
ax.plot_surface(theta1_grid, theta2_grid, loss_grid)

plt.show()

2. Implementation Details

A collaborator suggested trying the code on Windows. Another user ran it successfully on a machine with Matplotlib 3.5, producing the plots shown below.

The two figures illustrate that the 2‑D loss curves render correctly, while the 3‑D surface may fail on low‑performance machines or with newer Matplotlib versions (e.g., 3.6+ where Axes3D(fig) is deprecated). Using Matplotlib 3.5 avoids the warning and produces the expected 3‑D plot.

3. Conclusion

This article demonstrates how to compute and visualize the logistic‑regression loss surface in Python, highlights version‑specific issues with Matplotlib’s 3‑D API, and provides a working example that runs on Matplotlib 3.5.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

machine learningPythonlogistic regressionMatplotlib3D Plot
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.