plt.plot 颜色重叠线(Matplotlib)

Color overlapped lines with plt.plot (Matplotlib)

如何配置 plt.plot 使重叠的线条颜色更深?
例如,我想使用 plt.plot 以这样一种方式显示样本,即在上图中可以看到的密度在下图中会很清楚。
从下面的图中很难理解大部分样本所在的位置

这是我用来生成示例的代码:

import numpy as np
import matplotlib.pyplot as plt

time = 100
n_samples = 7000
x = np.linspace(0, time, n_samples)
r1 = np.random.normal(0, 1, x.size)
r2 = np.random.uniform(-6, 6, x.size)
data = np.dstack((r1, r2)).flatten()

fig, axs = plt.subplots(2, 1, figsize=(9, 6))
axs[0].scatter(np.arange(len(data)), data, alpha=0.1)
axs[1].plot(np.arange(len(data)), data, alpha=0.2)
plt.show()

更新:分割并绘制成分离函数

您可以单独创建每条线段,然后绘制它们,而不是绘制一条大曲线。这样,重叠部分将通过透明度混合。

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

def plot_line_as_segments(xs, ys=None, ax=None, **kwargs):
    ax = ax or plt.gca()
    if ys is None:
        ys = xs
        xs = np.arange(len(ys))
    segments = np.c_[xs[:-1], ys[:-1], xs[1:], ys[1:]].reshape(-1, 2, 2)
    added_collection = ax.add_collection(LineCollection(segments, **kwargs))
    ax.autoscale()
    return added_collection

time = 100
n_samples = 7000
x = np.linspace(0, time, n_samples)
r1 = np.random.normal(0, 1, x.size)
r2 = np.random.uniform(-6, 6, x.size)
data = np.dstack((r1, r2)).flatten()

fig, axs = plt.subplots(2, 1, figsize=(9, 6))
axs[0].scatter(np.arange(len(data)), data, alpha=0.1)
axs[0].margins(x=0)

plot_line_as_segments(data, ax=axs[1], alpha=0.05)
axs[1].margins(x=0)
plt.show()