Python 中的 matplotlib.patches.regular polygon 类
原文:https://www.geesforgeks.org/matplotlib-patches-regular polygon-in-class-python/
Matplotlib 是 Python 中一个惊人的可视化库,用于数组的 2D 图。Matplotlib 是一个多平台数据可视化库,构建在 NumPy 数组上,旨在与更广泛的 SciPy 堆栈一起工作。
matplot lib.patches.regular polygon
matplotlib.patches.regular polygon 类用于添加正多边形面片。
语法:class matplotlib.patches.regular polygon(xy,numVertices,半径=5,方向=0,kwargs) 参数:**
xy: 一个长度为 2 的元组(x,y)的中心。
numVertices: 表示顶点数。
半径:从中心到每个顶点的距离。
方位:用于旋转多边形(以弧度为单位)。
下表列出了有效的 kwargs
例 1:
蟒蛇 3
import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
import numpy as np
coord = [[0, 0, 0],
[0, 1, -1],
[-1, 1, 0],
[-1, 0, 1],
[0, -1, 1],
[1, -1, 0],
[1, 0, -1]]
colors = [["Green"],
["Green"],
["Green"],
["Green"],
["Green"],
["Green"],
["Green"]]
labels = [['1'], ['2'],
['3'], ['4'],
['5'], ['6'],
['7']]
# Horizontal cartesian coords
hcoord = for c in coord]
# Vertical cartersian coords
vcoord = [2\. * np.sin(np.radians(60)) * (c[1] - c[2]) /3.
for c in coord]
fig, ax = plt.subplots(1)
ax.set_aspect('equal')
# Add some coloured hexagons
for x, y, c, l in zip(hcoord, vcoord, colors, labels):
# matplotlib understands lower
# case words for colours
color = c[0].lower()
hex = RegularPolygon((x, y),
numVertices = 6,
radius = 2\. / 3.,
orientation = np.radians(30),
facecolor = color,
alpha = 0.2,
edgecolor ='k')
ax.add_patch(hex)
# Also add a text label
ax.text(x, y + 0.2, l[0], ha ='center',
va ='center', size = 20)
# add scatter points in hexagon centers
ax.scatter(hcoord, vcoord, c =.lower()
for c in colors],
alpha = 0.5)
plt.show()
输出:
例 2:
蟒蛇 3
import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
from matplotlib.collections import PatchCollection
import numpy as np
xy = np.random.random((10, 2))
z = np.random.random(10)
patches = [RegularPolygon((x, y),
5, 0.1)
for x, y in xy]
collection = PatchCollection(patches,
array = z,
edgecolors ='brown',
lw = 2)
fig, ax = plt.subplots()
ax.patch.set(facecolor ='green')
ax.add_collection(collection)
ax.autoscale()
plt.show()
输出: