如何仅使用matplotlib绘制垂直散点图

2024-04-19 17:12:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在matplotlib中绘制垂直散射图,但在中找不到任何东西matplotlib.org/示例或者StackOverflow。在

我尝试了一些我自己的东西,但我错过了抖动。对于具有相同(或非常相似)Y分量的点,抖动会稍微改变X分量,因此它们不会重叠。有什么我可以用的或者我必须手动改变x组件吗?在

import numpy as np
from matplotlib import pyplot as plt

x = np.array([1,2,3])
l = ['A','B','C']
a = np.array([2,2,3])
b = np.array([3,3,4])
c = np.array([7,7,5])
d = (np.array(a) + np.array(b) + np.array(c)) / 3

plt.subplot(111)
plt.margins(0.2)
plt.xticks(x,l)
plt.plot(x, a, 'ro', label='a')
plt.plot(x, b, 'ro', label='b')
plt.plot(x, c, 'ro', label='c')
plt.plot(x, d, 'k_', markersize=15, label='avg')
plt.tight_layout()
plt.savefig('vertical_scatter')
plt.close()

这让我跟着

enter image description here

我在Seaborn找到这个。在

enter image description here

我只想用plotlib。在


Tags: orgimport示例roplotmatplotlibasnp
2条回答

就像我在评论中提到的,你可以根据相邻y点的距离来改变x值。较小的距离应映射到较大的x偏移。这可以用对数或其他函数来实现。在

import numpy as np
import matplotlib.pyplot as plt

n = 100
y = np.random.random(n)
x = np.ones(n)
x0 = x[0]

y = np.sort(y)
dist = np.diff(y)  # has one entry less than y
dist = np.hstack([dist, np.median(dist)])  # add random value to match shapes
x = np.log(dist)
x = (x - np.min(x)) / (np.max(x) - np.min(x))  # mapped to range from 0 to 1
x = x0 + 0.5*(x - 0.5)  # mapped to range from x0-1/4 to x0+1/4

plt.scatter(x,y)
plt.scatter(x+1,y)
plt.scatter(x+2,y)

plt.show()

enter image description here

下面是仅使用matplotlib的抖动示例。其基本思想是在x值上添加一些随机噪声。在

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rayleigh(scale=1, size=(30,4))
labels = list("ABCD")
colors = ["crimson", "purple", "limegreen", "gold"]

width=0.4
fig, ax = plt.subplots()
for i, l in enumerate(labels):
    x = np.ones(data.shape[0])*i + (np.random.rand(data.shape[0])*width-width/2.)
    ax.scatter(x, data[:,i], color=colors[i], s=25)
    mean = data[:,i].mean()
    ax.plot([i-width/2., i+width/2.],[mean,mean], color="k")

ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels)

plt.show()

enter image description here

相关问题 更多 >