散点图同一点重复几次python

时间:2016-06-11 02:51:47

标签: python matplotlib scatter-plot plotly

我正试图从字典下面绘制散点图:

data_dict = {12: [1, 17, 11, 17, 1, 14, 38], 13: [13, 6, 4, 6], 14: [15, 8, 20, 8, 7], 15: [2, 3, 3, 1], 16: [62, 13, 36, 3, 8, 99, 54], 17: [1], 18: [44, 30, 36, 14, 21, 13, 44, 1, 62, 36], 19: [5, 5], 20: [27, 42, 42, 18, 31, 55, 31, 55], 21: [59, 1, 42, 17, 66, 26, 18, 4, 36, 42, 20, 54, 44, 35]}

我使用以下代码绘制散点图,其中字典键是x值,值是相应的值。

for xe, ye in data_dict.iteritems():
    plt.scatter([xe] * len(ye), ye)

得到这个情节:

enter image description here

我希望能够区分在给定的x和y位置只有一个点而不是多个点。例如,对于x = 12,y = 1且17重复两次。我想通过数据点的颜色或大小来表示这种重复。

我找不到有关如何执行此操作的任何参考。我将不胜感激任何帮助或指导。

感谢。

1 个答案:

答案 0 :(得分:5)

您可以获取每个项目的.count()并根据该项目计算大小,然后使用命名参数s指定这些大小。如果您使用的是python 2,请将.items()更改为.iteritems()

http://i.imgur.com/b8rO75l.png

import matplotlib.pyplot as plt

data_dict = {12: [1, 17, 11, 17, 1, 14, 38], 13: [13, 6, 4, 6], 14: [15, 8, 20, 8, 7], 15: [2, 3, 3, 1], 16: [62, 13, 36, 3, 8, 99, 54], 17: [1], 18: [44, 30, 36, 14, 21, 13, 44, 1, 62, 36], 19: [5, 5], 20: [27, 42, 42, 18, 31, 55, 31, 55], 21: [59, 1, 42, 17, 66, 26, 18, 4, 36, 42, 20, 54, 44, 35]}
size_constant = 20

for xe, ye in data_dict.items():
    xAxis = [xe] * len(ye)

    #square it to amplify the effect, if you do ye.count(num)*size_constant the effect is barely noticeable
    sizes = [ye.count(num)**2.5 * size_constant for num in ye]
    plt.scatter(xAxis, ye, s=sizes)

plt.show()



这是具有更多重要性的数据的样子,因为你的数据集没有很多重复,很难显示效果。

data_dict = {5 : [1], 8 : [5,5,5], 11 : [3,3,3],  15 : [8,8,8,8,7,7], 19 : [12, 12, 12, 12, 12, 12]}

enter image description here

相关问题