[英]Python Scatter Plot - Overlapping data
您可以抖動值(添加一些隨機噪聲),以使它們不會完全在同一地點。
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randint(low=1,high=5,size=50)
y = np.random.randint(low=0,high=2,size=50)
jittered_y = y + 0.1 * np.random.rand(len(y)) -0.05
jittered_x = x + 0.1 * np.random.rand(len(x)) -0.05
plt.figure(figsize=(10,5))
plt.subplot(221)
plt.scatter(x,y,s=10,alpha=0.5)
plt.title('No Jitter')
plt.subplot(222)
plt.scatter(x,jittered_y,s=10,alpha=0.5)
plt.title('Y Jittered')
plt.subplot(223)
plt.scatter(jittered_x,y,s=10,alpha=0.5)
plt.title('X Jittered')
plt.subplot(224)
plt.scatter(jittered_x,jittered_y,s=10,alpha=0.5)
plt.title('Y and X Jittered')
plt.tight_layout();
如果您更喜歡確定性偏移,我創建了這個函數是為了解決一個類似的問題(這讓我在這里尋求答案)。 請注意,此功能僅適用於完全重疊的點。 但是,您很可能可以舍入您的點並稍微修改此函數以適應“足夠接近”的點。
希望這會有所幫助。
import numpy as np
def dodge_points(points, component_index, offset):
"""Dodge every point by a multiplicative offset (multiplier is based on frequency of appearance)
Args:
points (array-like (2D)): Array containing the points
component_index (int): Index / column on which the offset will be applied
offset (float): Offset amount. Effective offset for each point is `index of appearance` * offset
Returns:
array-like (2D): Dodged points
"""
# Extract uniques points so we can map an offset for each
uniques, inv, counts = np.unique(
points, return_inverse=True, return_counts=True, axis=0
)
for i, num_identical in enumerate(counts):
# Prepare dodge values
dodge_values = np.array([offset * i for i in range(num_identical)])
# Find where the dodge values must be applied, in order
points_loc = np.where(inv == i)[0]
#Apply the dodge values
points[points_loc, component_index] += dodge_values
return points
這是之前和之后的示例。
前:
后:
此方法僅適用於完全重疊的點(或者如果您願意以np.unique
查找匹配點的方式np.unique
點)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.