Plotting a dictionary with multiple values per key

前端 未结 3 1642
广开言路
广开言路 2021-01-20 03:42

I have a dictionary that looks like this:

1: [\'4026\', \'4024\', \'1940\', \'2912\', \'2916], 2: [\'3139\', \'2464\'], 3:[\'212\']...

For

3条回答
  •  逝去的感伤
    2021-01-20 03:59

    1) Repeat your x values

    plot expects a list of x values and a list of y values which have to have the same length. That's why you have to repeat the rank value several times. itertools.repeat() can do that for you.

    2) change your iterator

    iteritems() already returns a tuple (key,value). You don't have to use keys() and items().

    Here's the code:

    import itertools
    for rank, structs in b.iteritems():
        x = list(itertools.repeat(rank, len(structs)))
        plt.plot(x,structs,'ro')
    

    3) combine the plots

    Using your code, you'd produce one plot per item in the dictionary. I guess you rather want to plot them within a single graph. If so, change your code accrodingly:

    import itertools
    x = []
    y = []
    for rank, structs in b.iteritems():
        x.extend(list(itertools.repeat(rank, len(structs))))
        y.extend(structs)
    plt.plot(x,y,'ro')
    

    4) example

    Here's an example using your data:

    import itertools
    import matplotlib.pyplot as plt
    d = {1: ['4026', '4024', '1940', '2912', '2916'], 2: ['3139', '2464'], 3:['212']}
    x= []
    y= []
    for k, v in d.iteritems():
        x.extend(list(itertools.repeat(k, len(v))))
        y.extend(v)
    plt.xlim(0,5)
    plt.plot(x,y,'ro')
    

    enter image description here

提交回复
热议问题