Matplotlib 散点图

Matplotlib 有一个内置函数 scatter() 来创建散点图。散点图是一种将数据显示为点集合的图。点的位置取决于其二维值,其中每个值是水平或垂直维度上的位置。

散点图示例

import numpy as np
import matplotlib.pyplot as plt

# Create data
N = 500
x = np.random.rand(N)
y = np.random.rand(N)
colors = (0,0,0)
area = np.pi*3

# Plot
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Scatter plot pythonspot.com')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

![matplotlib-散点图](/img/Tutorial/Matplotlib/Matplotlib scatter plot.svg))

分组的散点图

数据可以分为几组。如下面的代码表示:

import numpy as np
import matplotlib.pyplot as plt

# Create data
N = 60
g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N))
g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N))
g3 = (0.3*np.random.rand(N),0.3*np.random.rand(N))

data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("coffee", "tea", "water") 

# Create plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for data, color, group in zip(data, colors, groups):
    x, y = data
    ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

plt.title('Matplot scatter plot')
plt.legend(loc=2)
plt.show()

![matplotlib 分组散点图](/img/Tutorial/Matplotlib/Matplotlib grouped scatter plots.svg))