图文并茂的Python散点图教程

看完本教程,就可以应付大多数情况下的柱状图绘制了。 声明:

  1. 需要读者了解一点Python列表的知识
  2. 教程借助于matplotlib库

散点图基础

必要的库

# 需导入要用到的库文件
import numpy as np  # 数组相关的库
import matplotlib.pyplot as plt  # 绘图库

绘制散点图

N = 10
x = np.random.rand(N)  # 包含10个均匀分布的随机值的横坐标数组,大小[0, 1]
y = np.random.rand(N)  # 包含10个均匀分布的随机值的纵坐标数组
plt.scatter(x, y, alpha=0.6)  # 绘制散点图,透明度为0.6(这样颜色浅一点,比较好看)
plt.show()

调整散点大小

N = 10
x = np.random.rand(N)
y = np.random.rand(N)
area = np.random.rand(N) * 1000  # 包含10个均匀分布的随机值的面积数组,大小[0, 1000]
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5)  # 绘制散点图,面积随机
plt.show()

调整散点颜色

N = 10
x = np.random.rand(N)
y = np.random.rand(N)
x2 = np.random.rand(N)
y2 = np.random.rand(N)
area = np.random.rand(N) * 1000
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5)
ax.scatter(x2, y2, s=area, c=green, alpha=0.6)  # 改变颜色
plt.show()

调整散点形状

N = 10
x = np.random.rand(N)
y = np.random.rand(N)
x2 = np.random.rand(N)
y2 = np.random.rand(N)
x3 = np.random.rand(N)
y3 = np.random.rand(N)
area = np.random.rand(N) * 1000
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5)
ax.scatter(x2, y2, s=area, c=green, alpha=0.6)
ax.scatter(x3, y3, s=area, c=area, marker=v, cmap=Reds, alpha=0.7)  # 更换标记样式,另一种颜色的样式
plt.show()
这里要解释一下,大家可能注意到了:图片中的红色倒三角,面积越大的颜色越红。这是因为我们在ax.scatter()中启用了参数cmap,它需要与控制颜色的参数c配合使用。cmap指明调色板的类型,c指明颜色的深浅。 调色板的类型可见:

调整散点边界

N = 10
x = [1]
y = [1]
x2 = [1.1]
y2 = [1.1]
x3 = [0.9]
y3 = [0.9]
area = [20000]
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5, edgecolors=face)
ax.scatter(x2, y2, s=area, linewidths=[3])
ax.scatter(x3, y3, s=area, alpha=0.5, linewidths=[3], edgecolors=r)
plt.show()
经验分享 程序员 微信小程序 职场和发展