matplotlib可视化之Scatter散点图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了matplotlib可视化之Scatter散点图相关的知识,希望对你有一定的参考价值。

参考技术A Scatter chart(PointGraph, X-Y Plot, Scatter Chart或者 Scattergram)是绘图中最常见的图形类型之一,通常用于显示和比较数值。散点图是使用一系列的散点在直角坐标系中展示变量的数值分布。在二维散点图中,可以通过观察两个变量的数据分析,发现两者的关系与相关性。

散点图可以提供三类关键信息:
(1)变量之间是否存在数量关联趋势(正相关,负相关,不相关等);
(2)如果存在关联趋势,是线性还是非线性的;
(3)观察是否有存在离群值,从而分析这些离群值对建模分析的影响。

scatter的详细定义: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html?highlight=scatter#matplotlib.pyplot.scatter

散点图 scatter

第三章 散点图 scatter

参考自官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.scatter.html#matplotlib.axes.Axes.scatter

matplotblib 绘制散点图常用参数:

  • x, y:一个或者多个点的位置;
  • s:标记大小(以点**2为单位)(印刷点为1/72;
  • c:标记颜色。可选值:
    • 使用cmap和范数将n个数字的标量或序列映射到颜色。
    • 行为RGB或RGBA的2D阵列。
    • 长度为n的一系列颜色。
    • 单色格式字符串。
  • marker:标记样式,默认 "o",更多标记符号参考 https://matplotlib.org/stable/api/markers_api.html#module-matplotlib.markers
  • cmap:用于将标量数据映射到颜色的Colormap实例或注册的Colormap名称。
  • norm:在使用cmap映射到颜色之前,用于将标量数据缩放到[0,1]范围的归一化方法。默认情况下,使用线性缩放,将最小值映射到0,将最大值映射到1。
  • alpha:alpha混合值,介于0(透明)和1(不透明)之间。
  • linewidths:线条粗细。
  • edgecolors:边缘颜色。可选 'face', 'none', None

3.1 官方例子

以下例子来自 matplotlib 官方

https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_demo2.html#sphx-glr-gallery-lines-bars-and-markers-scatter-demo2-py

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook

# Load a numpy record array from yahoo csv data with fields date, open, high,
# low, close, volume, adj_close from the mpl-data/sample_data directory. The
# record array stores the date as an np.datetime64 with a day unit ('D') in
# the date column.
price_data = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
              .view(np.recarray))
price_data = price_data[-250:]  # get the most recent 250 trading days

delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1]

# Marker size in units of points^2
volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2
close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]

fig, ax = plt.subplots()
ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)

ax.set_xlabel(r'$\\Delta_i$', fontsize=15)
ax.set_ylabel(r'$\\Delta_i+1$', fontsize=15)
ax.set_title('Volume and percent change')

ax.grid(True)
fig.tight_layout()

plt.show()

绘制的效果如下:


这个例子需要注意以下几个方面:

  • 官方的例子基本上都不再直接使用 plt 直接进行绘制,而是在 figure() 后返回的第二个对象进行操作;
  • 并且这里提供了 latex 公式的转换功能;
  • 当遇到这方面的需求,比如绘制论文实验图片,可以考虑参考这个例子。

3.2 官方例子 2

https://matplotlib.org/stable/plot_types/basic/scatter_plot.html#sphx-glr-plot-types-basic-scatter-plot-py

这个例子更加简单,代码如下:

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('_mpl-gallery')

# make the data
np.random.seed(3)
x = 4 + np.random.normal(0, 2, 24)
y = 4 + np.random.normal(0, 2, len(x))
# size and color:
sizes = np.random.uniform(15, 80, len(x))
colors = np.random.uniform(15, 80, len(x))

# plot
fig, ax = plt.subplots()

ax.scatter(x, y, s=sizes, c=colors, vmin=0, vmax=100)

ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
       ylim=(0, 8), yticks=np.arange(1, 8))

plt.show()

绘制效果如下:

3.3 线性回归例子

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


x = np.arange(0.0, 50.0, 2.0)
y = x ** 2 + np.random.rand(*x.shape) * 30.0
sizes = np.random.rand(*x.shape) * 800 + 500

fig, ax = plt.subplots()
ax.scatter(x, y, sizes, c="green", alpha=0.5, marker=r'$\\clubsuit$',
           label="Luck")
ax.set_xlabel("Leprechauns")
ax.set_ylabel("Gold")
ax.legend()
plt.show()

绘制结果为:

3.4 多类型散点图

这里以三类散点图为例

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(19680801)


fig, ax = plt.subplots()
for color in ['tab:blue', 'tab:orange', 'tab:green']:
    n = 50
    x, y = np.random.rand(2, n)
    scale = 200.0 * np.random.rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')

ax.legend()
ax.grid(True)

plt.show()

绘制结果为:

3.5 极轴上的散点图

摘录自 https://matplotlib.org/stable/gallery/pie_and_polar_charts/polar_scatter.html#sphx-glr-gallery-pie-and-polar-charts-polar-scatter-py

import numpy as np
import matplotlib.pyplot as plt


# Fixing random state for reproducibility
np.random.seed(19680801)

# Compute areas and colors
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta

fig = plt.figure()
ax = fig.add_subplot(projection='polar')
c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)
plt.show()

绘制效果如下:


类似图片的绘制推荐参考官网地址:https://matplotlib.org/stable/gallery/pie_and_polar_charts/polar_scatter.html#sphx-glr-gallery-pie-and-polar-charts-polar-scatter-py


3.6 三维散点图

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


def randrange(n, vmin, vmax):
    """
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    """
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

绘制效果如下:

3.7 本章总结

绘制自己需要的散点图的步骤大致如下:

  1. 明确自己需要绘制的散点图类型;
  2. 确保待绘制图片的数据没有问题;
  3. 复制类似的例子源码,根据参数说明修改参数,绘制符合个性化需求的图片。

Smileyan
2022.12.6 22:00

以上是关于matplotlib可视化之Scatter散点图的主要内容,如果未能解决你的问题,请参考以下文章

Python使用matplotlib可视化散点图使用seaborn中的lmplot函数可视化不同分组散点图的最优线性回归拟合曲线(Scatter plot with regression line)

python使用matplotlib可视化使用scatter函数可视化散点图并使用s参数设置数据点的大小(change size of points)

python使用matplotlib可视化散点图(scatter plot)根据matplotlib中数据点的值更改数据点的颜色数值更大的点颜色更深

pandas散点图-plot.scatter

使用matplotlib中scatter()绘制散点图

matplotlib 散点图scatter