<p>我做了一些调整。它们在代码中有注释:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
import matplotlib as mpl
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(111)
s = 100 # Plot size (100, 100)
min = 10 # Min rectangle height
max = 20 # Max rectangle height
degree = np.random.randint(0, 360) # Random rectangle rotation
background = np.random.randint(0, 256, (s, s, 3)) # Random background pixels
a = np.random.randint(min, max) # Little side of rectangle
b = np.random.randint(a*1.5, a*2.5) # Big side of rectangle
cx = np.random.randint(0 + a, s - a) # Random horizontal location
cy = np.random.randint(0 + a, s - b) # Random vertical location
pt = patches.Rectangle((cx,cy), a, b, color="white", alpha=0.7) # Rectangle with random sides and location
rt = mpl.transforms.Affine2D().rotate_deg_around(cx+a/2, cy+b/2, degree) + ax.transData # Set random rotation
pt.set_transform(rt) # Use random rotation to rotate rectangle
ax.add_patch(pt) # Add rectangle to plot
background[0, 0] = np.random.randint(200, 255, background[0, 0].shape)
plt.imshow(background)
plt.xlim(0, s)
plt.ylim(0, s)
plt.title('Random Square')
plt.show()
</code></pre>
<p>输出:</p>
<p><a href="https://i.stack.imgur.com/csyHR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/csyHR.png" alt="Output image"/></a></p>