Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

Given a list looking like this:

triangels =  [

((1,1,1),(2,2,2),(1,3,4)),

((2,3,4),(9,9,9),(3,4,5)),

]

What is the fastest way to plot both triangles in 3D using pyplot? I do not find any way doing this, there is a 2D implementation.

Thank you!

This is not a duplicate since I asked how to convert the given list into triangles, I did not ask for a solution where the input is already manipulated.

1 Answer

0 votes
by (41.4k points)

Here is a solution that will give you exactly what you want:

from itertools import chain

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

triangles =  [

    ((1, 1, 1), (2, 2, 2), (1, 3, 4)),

    ((2, 3, 4), (9, 9, 9), (3, 4, 5)),

]

# Convert the list of triangles into a "flat" list of points

tri_points = list(chain.from_iterable(triangles))

# Get the X, Y and Z coordinates of each point

x, y, z = zip(*tri_points)

# Make list of triangle indices ([(0, 1, 2), (3, 4, 5), ...])

tri_idx = [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(len(triangles))]

# Make 3D axes

ax = plt.figure().gca(projection='3d')

# Plot triangles

ax.plot_trisurf(x, y, z, triangles=tri_idx)

If you wish to learn more about Python visit this Python Tutorial.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...