Search code examples
pythonmatplotlibbubble-chart

Square bubble map


I'm hoping to make a bubble map, but instead of circles to have squares whose areas are scaled to their value. So something like this:

enter image description here

Is that possible with Matplotlib? Or can bubble maps only consist of circles?


Solution

  • This code recreates some of the features you have on your example chart, using matplotlib's plot() function, taking advantage of the marker options:

    import matplotlib.pyplot as plt
    import numpy as np
    import random
    
    xs = np.arange(1, 5, 1)
    ys = np.arange(0.5, 6, 1)
    
    colors = ["gray", "red", "green"]
    
    def square_size_color(value):
    
        square_color = random.choice(colors)
    
        if value < 1:
            square_size = random.choice(range(1, 10))
        if 3 > value > 1:
            square_size = random.choice(range(10, 25))
        else:
            square_size = random.choice(range(25, 35))
    
        return square_size, square_color
    
    
    for x in xs:
        for y in ys:
            square_size, square_color = square_size_color(y)
            plt.plot(x, y, linestyle="None", marker="s",  # 's' for square marker
                     markersize=square_size, mfc=square_color, mec=square_color)
    
    plt.grid(visible=True, axis='y')
    plt.xlim(0.5, 4.5)
    plt.ylim(-0.5, 6.5)
    plt.show()
    

    This will produce something like:

    enter image description here

    Although there may be a more direct way of doing this, I believe this will work for what you want to do. Obviously, you can customize the conditions for sizes and colors, and I used the random.choice() just so the chart looks prettier.