Drawing a Circle Inside a Hexagon in Python

Drawing geometric shapes, especially when one is nested inside another, can be an engaging task for both educational and recreational purposes. In Python, we can accomplish this using libraries such as matplotlib for plotting and numpy for numerical computations. This article will guide you through drawing a circle inside a hexagon using these libraries.

First, let’s ensure we have the necessary libraries installed. If you haven’t installed them yet, you can do so using pip:

bashCopy Code
pip install matplotlib numpy

Next, we will import the required modules and set up our canvas:

pythonCopy Code
import numpy as np import matplotlib.pyplot as plt import matplotlib.path as mpath fig, ax = plt.subplots()

To draw a hexagon, we need to calculate the vertices. A hexagon can be imagined as divided into 4 triangles, each with an angle of 60 degrees at the center. We can use polar coordinates to find the vertices and then convert them to Cartesian coordinates:

pythonCopy Code
# Radius of the hexagon r = 1 # Number of vertices n = 6 # Calculate the vertices vertices = [(r * np.cos(2 * np.pi * i / n), r * np.sin(2 * np.pi * i / n)) for i in range(n)] codes = [mpath.Path.MOVETO] + [mpath.Path.LINETO] * (n-1) + [mpath.Path.CLOSEPOLY] path = mpath.Path(vertices, codes)

Now, let’s draw the hexagon using the calculated vertices:

pythonCopy Code
ax.plot(*zip(*vertices), marker='o') # Drawing the hexagon

For the circle, we simply need to specify the center and the radius. We’ll use the same radius as the hexagon for simplicity:

pythonCopy Code
circle = plt.Circle((0, 0), r, fill=False) ax.add_artist(circle)

Finally, we’ll set the limits of our plot to ensure the entire hexagon is visible and show the plot:

pythonCopy Code
ax.set_xlim(-1.5, 1.5) ax.set_ylim(-1.5, 1.5) ax.set_aspect('equal', adjustable='box') plt.grid() plt.show()

Executing the above code will render a plot showing a circle neatly fitted inside a hexagon. This basic example can be extended to explore various geometric relationships, such as changing the radius of the circle or adjusting the orientation of the hexagon.

[tags]
Python, Matplotlib, Numpy, Geometry, Drawing Shapes, Hexagon, Circle

78TP Share the latest Python development tips with you!