欢迎访问宙启技术站
智能推送

Python生成随机的几何形状示例

发布时间:2023-12-12 03:17:04

Python中可以使用matplotlib库来生成随机的几何形状。下面是生成随机的矩形、圆形和多边形的示例代码:

1. 生成随机矩形:

import matplotlib.pyplot as plt
import random

# 生成随机的矩形
def generate_random_rectangle():
    x = random.randint(0, 10)
    y = random.randint(0, 10)
    width = random.randint(1, 5)
    height = random.randint(1, 5)
    return (x, y, width, height)

# 绘制矩形
def draw_rectangle(rectangle):
    x, y, width, height = rectangle
    plt.gca().add_patch(plt.Rectangle((x, y), width, height, fill=None, edgecolor='red'))

# 绘制100个随机矩形
for _ in range(100):
    rectangle = generate_random_rectangle()
    draw_rectangle(rectangle)

plt.axis('scaled')
plt.show()

2. 生成随机圆形:

import matplotlib.pyplot as plt
import random

# 生成随机圆形
def generate_random_circle():
    center_x = random.uniform(0, 10)
    center_y = random.uniform(0, 10)
    radius = random.uniform(1, 5)
    return (center_x, center_y, radius)

# 绘制圆形
def draw_circle(circle):
    center_x, center_y, radius = circle
    plt.gca().add_patch(plt.Circle((center_x, center_y), radius, fill=None, edgecolor='blue'))

# 绘制100个随机圆形
for _ in range(100):
    circle = generate_random_circle()
    draw_circle(circle)

plt.axis('scaled')
plt.show()

3. 生成随机多边形:

import matplotlib.pyplot as plt
import random

# 生成随机多边形
def generate_random_polygon():
    num_points = random.randint(3, 6)
    points = []
    for _ in range(num_points):
        x = random.random() * 10
        y = random.random() * 10
        points.append((x, y))
    return points

# 绘制多边形
def draw_polygon(polygon):
    x, y = zip(*polygon)
    plt.gca().add_patch(plt.Polygon(list(zip(x, y)), fill=None, edgecolor='green'))

# 绘制100个随机多边形
for _ in range(100):
    polygon = generate_random_polygon()
    draw_polygon(polygon)

plt.axis('scaled')
plt.show()

这些示例代码演示了如何使用matplotlib库在Python中生成随机的矩形、圆形和多边形。你可以自由调整随机参数的范围和个数来创建不同形状的图形。