Search code examples
pythonmatplotlibdefaultdict

How to extract and plot the keys of a defaultdict based on the values


I am using defalutdict (ddtype in the code) objects, that basically work as a three-dimensional function, by mapping each couple of natural elements into a real number.

But if I try to use matplotlib to print all the elements with some characteristics:

import matplotlib.pyplot as plt
from collections import defaultdict

ddtype = defaultdict(int, {(1,1):2.2,(1,2):0.7,(2,1):0.9,(2,2):1.3})

for i in range(1,3):
    for j in range(1,3):
        if (ddtype[i,j] > 1.5):
            plt.plot((i,j),'k+')

plt.show()
# The plot is saved but not here

then the program becomes very slow (for big ranged cycles) even though I clear the memory frequently. Is it there a more efficient way to write the above loop? Thank you in advance


Solution

    • Unpack the filtered i and j into separate containers, and then plot.
      • Processing the defaultdict separately, and then only plotting once, should be faster than accessing the plot object multiple times.
    • Collect the desired tuples with a list comprehension:
      • [k for k, v in ddtype.items() if v > 1.5]
    • Unpack the tuples into separate objects:
    from collections import defaultdict as dd
    import matplotlib.pyplot as plt
    
    ddt = dd(int, {(1, 1): 2.2, (1, 2): 0.7, (2, 1): 0.9, (2, 2): 1.3})
    
    i, j = zip(*[k for k, v in ddt.items() if v > 1.5])
    
    plt.plot(i, j, 'k+')
    

    enter image description here