# 导入对应的模块
from matplotlib import lines
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# 1、定义线图例
# 方法1
line1 = lines.Line2D([0], [0], label='line1', marker='o', lw=2, c='green')
# 方法2,注意别丢逗号
line2, = plt.plot([0], [0], label='line2', marker='X', lw=2, c='blue')
# 2、定义矩形图例
path1 = mpatches.Patch(color="red", label="patch")
# 3、定义散点图图例
s1 = plt.scatter([0], [0], label='scatter', marker='+')
# 4、显示图例
handles = [line1, path1, line2, s1]
fig, ax = plt.subplots(figsize=(6.4, 0.32)) # 根据行数更改0.32
# ax.legend(handles=handles, labels=["a","b","c","d"], mode="expand", ncol = 4, borderaxespad = 0) # mode='expand', 水平展示图例
ax.legend(handles=handles, mode="expand", ncol = 4, borderaxespad = 0)
ax.axis("off") # 去掉坐标刻度
plt.show()
ax = plt.gca() #返回坐标轴
plt.legend(scatterpoints=1,labels = Label_Com, labelspacing=0.4,columnspacing=0.4,markerscale=2,bbox_to_anchor=(0.9, 0),ncol=12,prop=font1,handletextpad=0.1)
即先创建一个ax = plt.gca(),在ax的基础上操作即可创建组图的共享图例。
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
labels = ['winter', 'spring', 'summer', 'autumn']
color = ['lightskyblue', 'lime', 'red', 'gold']
patches = [mpatches.Patch(color=color[i], label="{:s}".format(labels[i])) for i in range(len(color))]
ax = plt.gca()
# 下面一行中bbox_to_anchor指定了legend的位置
ax.legend(handles=patches, bbox_to_anchor=(0.95, 1.12), ncol=4) # 生成legend
plt.show()