Python Programs

Draw Triangle In Python Using Matplotlib

Published November 11, 2023 by Jarvis Silva

In this python tutorial I will show you how to draw a trianlge in python using matplotlib module, Matplotlib allows plotting in python so to plot triangle in matplotlib we will also use numpy so let’s see how to create this program.

First we need to install Matplotlib and Numpy in our system so to install use below commands.

# Install matplotlib
pip install matplotlib

# Install numpy
pip install numpy

Above commands will install both libraries in your system now let’s see the code

Python Code To Draw Triangle Using Matplotlib

import matplotlib.pyplot as plt
import numpy as np

# Define the vertices of the triangle
vertices = np.array([[0, 0], [1, 0], [0.5, 1]])

# Close the triangle by repeating the first vertex at the end
vertices = np.vstack([vertices, vertices[0]])

# Plot the triangle
plt.plot(vertices[:, 0], vertices[:, 1], marker='o')

# Set axis limits
plt.xlim(0, 1)
plt.ylim(0, 1)

# Set labels and title
plt.title('Triangle in Matplotlib')

# Show the plot

Above is the python code for drawing triangle in matplotlib, if you run the above code it will plot a triangle.