通过值重复进行散点图或气泡图

问题描述 投票:0回答:1

我有一组数字序列,保存在二维列表中。列表中的每个元素都是不同长度的子列表,例如 1-10 范围内的数字。像这样:

Lst = [[1,3,4,4,4,5],[2,7,2,3],[6,5,4,2,4],[2,4,5,7,5,4,2],[4,9,4,1,4,5,4]…]

有没有办法使用 matplotlib 以具有重复值的散点图或气泡图绘制这些数据?列表中的每个元素在X轴上占据一个位置,元素中的所有值都分布在对应的Y轴位置上,并且该值重复的次数越多,绘制的尺寸越大或颜色越深点。

我已经知道如何使用 matplotlib 散点图绘制,但我不知道如何在一个 Y 轴上一一绘制 2D 列表项。

谢谢你。

python matplotlib scatter-plot bubble-chart
1个回答
1
投票

您可以在 for 循环中绘制每个子列表:

import matplotlib.pyplot as plt
from collections import Counter
import numpy as np
Lst = [[1,3,4,4,4,5],[2,7,2,3],[6,5,4,2,4],[2,4,5,7,5,4,2],[4,9,4,1,4,5,4]]
plt.figure()
for i, j in enumerate(Lst):
    occurences, sizes = list(zip(*list(Counter(j).items())))
    plt.scatter(i*np.ones(len(occurences))+1, occurences, s=np.array(sizes)*50)

输出:

编辑:满足点也变暗的要求。使用这里的答案:在 matplotlib 中变暗或变亮颜色

import matplotlib.pyplot as plt
from collections import Counter
import numpy as np

def lighten_color(color, amount=0.5):
    """
    Lightens the given color by multiplying (1-luminosity) by the given amount.
    Input can be matplotlib color string, hex string, or RGB tuple.

    Examples:
    >> lighten_color('g', 0.3)
    >> lighten_color('#F034A3', 0.6)
    >> lighten_color((.3,.55,.1), 0.5)
    """
    import matplotlib.colors as mc
    import colorsys
    try:
        c = mc.cnames[color]
    except:
        c = color
    c = colorsys.rgb_to_hls(*mc.to_rgb(c))
    return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])

Lst = [[1,3,4,4,4,5],[2,7,2,3],[6,5,4,2,4],[2,4,5,7,5,4,2],[4,9,4,1,4,5,4]]
occurences, sizes = list(zip(*[list(zip(*list(Counter(j).items()))) for j in Lst]))
maximum = max(max(i) for i in sizes)

plt.figure()
for i, (j, k) in enumerate(zip(occurences, sizes)):
    plt.scatter(i*np.ones(len(j))+1, j, s=np.array(k)*50, color=[lighten_color('b', 2*m/maximum) for m in k])

输出:

© www.soinside.com 2019 - 2024. All rights reserved.