Matplotlib| scatter函数

1. 简介

Matplotlib 库中的 scatter 函数用于在坐标轴上创建散点图。这种图表显示了两个变量之间的关系,每个点代表了数据集中的一个观测值。scatter 函数通常用于探索数据,特别是要查看两个变量是否存在某种相关性或模式。

基本用法是 scatter(x, y),其中 xy 是长度相同的数组或列表,分别代表散点图中点的横坐标和纵坐标。

此外,scatter 函数还提供了多种可选参数来定制散点图的外观,例如:

  • c: 设置点的颜色。
  • s: 设置点的大小。
  • marker: 设置点的形状。
  • alpha: 设置点的透明度。

2. 基础散点图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 2, 4, 5]
plt.scatter(x, y)
plt.title('Basic Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()

Matplotlib| scatter函数_第1张图片

3. 自定义外观

import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()  # 显示颜色比例尺
plt.title('Customized Scatter Plot')
plt.show()

Matplotlib| scatter函数_第2张图片

4. 分组和多类别

import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x1 = np.random.rand(50)
y1 = np.random.rand(50)
x2 = np.random.rand(50)
y2 = np.random.rand(50)

plt.scatter(x1, y1, c='blue', label='Category A')
plt.scatter(x2, y2, c='green', label='Category B')

plt.title('Multi-category Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.legend()
plt.show()

Matplotlib| scatter函数_第3张图片

实在是太好用了
Matplotlib官方文档: link

以上

你可能感兴趣的:(matplotlib)