简体   繁体   English

用 plt.plot 颜色重叠线(Matplotlib)

[英]Color overlapped lines with plt.plot (Matplotlib)

How can I configure plt.plot such that overlapped lines will have darker colors?我如何配置plt.plot使重叠的线条更暗 colors?
For example, I would like to use plt.plot to display the samples in such a way that the density that can be seen in the upper plot will be clear in the lower plot.例如,我想使用plt.plot以这样一种方式显示样本,即在上面的 plot 中可以看到的密度在下面的 plot 中会很清楚。
From the lower plot it's hard to understand where most of the samples are located从下面的 plot 很难理解大部分样本的位置

情节示例

Here is the code I used in order to generate the example:这是我用来生成示例的代码:

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()

I found this code:我找到了这段代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
 
data = np.random.normal(10,3,100) # Generate Data
density = gaussian_kde(data)
 
x_vals = np.linspace(0,20,200) # Specifying the limits of our data
density.covariance_factor = lambda : .5 #Smoothing parameter
 
density._compute_covariance()
plt.plot(x_vals,density(x_vals))
plt.show()

From: https://www.askpython.com/python/examples/density-plots-in-python来自: https://www.askpython.com/python/examples/density-plots-in-python

Instead of drawing one large curve, you could create each line segment separately and then draw these.您可以单独创建每个线段,然后绘制它们,而不是绘制一条大曲线。 That way, the overlapping segments will be blended via the transparency.这样,重叠部分将通过透明度混合。

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

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)

xs = np.arange(len(data))
ys = data
segments = np.c_[xs[:-1], ys[:-1], xs[1:], ys[1:]].reshape(-1, 2, 2)
axs[1].add_collection(LineCollection(segments, alpha=0.05))
axs[1].autoscale()
axs[1].margins(x=0)
plt.show()

绘制单个段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM