Joan Venge
Joan Venge

Reputation: 330852

How to draw grid planes uniformly using matplotlib?

Basically I have this code:

import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations

fig = plt.figure()
ax = fig.add_subplot(1,1,1,projection='3d')

but that gets me this result:

enter image description here

whereas I want something like this (without the 3d cube):

enter image description here

In my picture you can see the grid plane lines are too close to each other at the plane intersections. I want them to positioned uniformly starting at the 3d grid origin.

Upvotes: 0

Views: 56

Answers (1)

m4rsland
m4rsland

Reputation: 15

When using these graphics, you can manually zoom by dragging the mouse and holding right click. This, in return, will move the grid lines. This means that "setting" a predetermined "zoom level" is the real problem. Here is a quick example I did. You can adjust it to how you need it.

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

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

# Define the range of the data
x_range = (0, 1)
y_range = (0, 1)
z_range = (0, 1)

# Set zoom percentage (e.g., zoom to 50% of the data range)
zoom_percentage = 0.5

# Calculate new limits based on zoom percentage
def calculate_zoom_limits(data_range, percentage):
    center = (data_range[0] + data_range[1]) / 2
    half_span = (data_range[1] - data_range[0]) * percentage / 2
    return (center - half_span, center + half_span)

x_limits = calculate_zoom_limits(x_range, zoom_percentage)
y_limits = calculate_zoom_limits(y_range, zoom_percentage)
z_limits = calculate_zoom_limits(z_range, zoom_percentage)

# Set the limits based on zoom percentage
ax.set_xlim(x_limits)
ax.set_ylim(y_limits)
ax.set_zlim(z_limits)

# Enable grid
ax.grid(True)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# Show the plot
plt.show()

I hope this helped.

Upvotes: 2

Related Questions