如何配置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()
uj5u.com熱心網友回復:
更新:分割并繪制成分離的函式
您可以單獨創建每條線段,然后繪制它們,而不是繪制一條大曲線。這樣,重疊的部分將通過透明度混合。
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()

uj5u.com熱心網友回復:
我找到了這個代碼:
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()
來自:https : //www.askpython.com/python/examples/density-plots-in-python
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/402805.html
標籤:
上一篇:DICOM影像讀取不正確
