Matplotlib中的自动图例创建

Matplotlib中的自动图例创建

要在Matplotlib中自动创建图例,我们可以执行以下步骤-

  • 设置图形大小并调整子图之间和周围的填充。
  • 为样本数据数量初始化变量 N。
  • 使用numpy创建 x,y,cs 数据。
  • 使用 subplots() 方法创建一个图形和子图集。
  • 使用不同的颜色和大小绘制 x,y 数据点。
  • 在轴上放置图例。
  • 向图形添加 artist。
  • 为PathCollection创建图例句柄和标签。
  • 再次在轴上放置一个大小的图例。
  • 要显示图形,请使用 show() 方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 45
x, y = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=c, s=s)
legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes")
ax.add_artist(legend1)
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes")

plt.show()

输出

Matplotlib中的自动图例创建

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程