1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| from __future__ import division
import matplotlib.pyplot as plt
import matplotlib.patches as ptc
from random import random
def plot_rectangle(vtxs, values):
"""plot a rectangle with matplotlib
vtxs : list of vertices [[(x1,y1), (x2,y2), ...]
values : value associated with the rectangle. Must be
between 0.0 and 1.0 (normalized)
"""
# Create a figure and a 'plot' inside it.
fig = plt.figure(1)
ax = fig.add_subplot(111)
for vtx, value in zip(vtxs, values):
# Create a rectangle. Size defined as lower left coordinates +
# width + height
x0, y0 = vtx[0]
width = vtx[2][0] - vtx[0][0]
height = vtx[2][1] - vtx[0][1]
rectangle = ptc.Rectangle(
(x0, y0),
width,
height,
# Color option, alpha to play with transparency
color=plt.cm.gray(value), alpha=0.5,
# Option to handle patches overlapping.
zorder=0
)
# Add the rectangle patch to the plot
ax.add_artist(rectangle)
# Set axis limits to see something
ax.set_xlim((0, 1))
ax.set_ylim((0, 1))
ax.grid(True)
plt.show()
# Example
n_rectangles = 10
vertices = [[(random(), random()), (random(), random()), (random(),
random()), (random(), random())] for i in range(n_rectangles)]
values = [random() for i in range(n_rectangles )]
plot_rectangle(vertices, values) |
Partager