1.生成形状
代码如下:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig,ax = plt.subplots()
xy1 = np.array([0.2, 0.2])
xy2 = np.array([0.2, 0.8])
xy3 = np.array([0.8, 0.2])
xy4 = np.array([0.8, 0.8])
# 圆形:圆心坐标为xy1,半径为0.05
circle = mpatches.Circle(xy1,0.05)
ax.add_patch(circle)
# 矩形:左下角纵坐标,宽和高
rect = mpatches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)
# 多边形
plygon = mpatches.RegularPolygon(xy3,5,0.1,color='g')
ax.add_patch(plygon)
# 椭圆
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color='y')
ax.add_patch(ellipse)
plt.axis('equal')
plt.grid(True)
plt.show()
运行结果
2.美化图形
import numpy as np
import matplotlib.pyplot as plt
# ggplot美化图形
plt.style.use('ggplot')
fig, axes = plt.subplots(ncols=2, nrows=2)
ax1, ax2, ax3, ax4 = axes.ravel()
# 两行十列的数组
x, y = np.random.normal(size=(2, 100))
# print(plt.style.available)可以查看左右样式
ax1.plot(x, y, 'o')
x = np.arange(0, 10)
y = np.arange(0, 10)
ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, 10, ncolors)
for s in shift:
ax2.plot(x, y + s, '-')
x = np.arange(5)
y1, y2, y3 = np.random.randint(1, 25, size=(3, 5))
width = 0.25
ax3.bar(x, y1, width)
ax3.bar(x + width, y2, width)
ax3.bar(x + 2 * width, y3, width)
for i, color in enumerate(plt.rcParams['axes.prop_cycle']):
print(color)
xy = np.random.normal(size=2)
ax4.add_patch(plt.Circle(xy, radius=0.3, color=color['color']))
ax4.axis('equal')
plt.show()
运行结果