简体   繁体   English

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

[英]How to plot vertical scatter using only matplotlib

I need to plot vertical scatters in matplotlib but I couldn't find anything in matplotlib.org/examples or StackOverflow. 我需要在matplotlib中绘制垂直散点图,但在matplotlib.org/examples或StackOverflow中找不到任何内容。

I tried something of my own but I am missing Jitter. 我尝试了一些自己的尝试,但我错过了抖动。 Jitter changes X component slightly for the points having same (or very similar) Y components so they won't overlap. 对于具有相同(或非常相似)Y分量的点,抖动会稍微改变X分量,因此它们不会重叠。 Is there anything which I can use or will I have to change x components manually? 我有什么可以使用的,还是必须手动更改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()

which gave me following 这给了我以下

在此处输入图片说明

I found this on Seaborn . 我在Seaborn上找到了这个。

在此处输入图片说明

which is what I want but only using matplotlib. 这是我想要的,但仅使用matplotlib。

An example with jitter using only matplotlib would be the following. 下面是一个仅使用matplotlib进行抖动的示例。 The idea is basically to add some random noise to the x values. 这个想法基本上是在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()

在此处输入图片说明

Like I mentioned in my comment, you could shift the x-values according to the distance of neighboring y-points. 就像我在评论中提到的那样,您可以根据相邻y点的距离移动x值。 Smaller distances should be mapped to a larger x-shift. 较小的距离应映射为较大的x位移。 This can be done with a logarithm or another function doing that. 这可以用对数或其他函数完成。

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

在此处输入图片说明

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

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