Search code examples
pythonmatplotlibbubble-chart

Bubble Chart Title and Colors


In the following bubble chart, how can I:

  1. Randomize the color of each bubble

  2. Adjust the title (maybe upper) so it will not overlap with the graph tag on the far up left corner.

Here is my output:

Bubble Chart

Here is my code:

import matplotlib.pyplot as plt
N=5
province=['Ontario','Quebec','BritishColumbia','Manitoba','NovaScoti']
size = [908.607,1356.547,922.509,552.329,651.036]
population = [12851821,7903001,4400057,1208268,4160000]
injuries = [625,752,629,1255,630]
plt.scatter(size,population,s=injuries)
for i in range(N):
    plt.annotate(province[i],xy=(size[i],population[i]))
plt.xlabel('Size(*1000km2)')
plt.ylabel('Population(ten million)')
plt.title('The Car Accidents Injuries Rate in 5 Canada Provinces')
plt.show

Solution

    1. You can feed an array of N random numbers to a colormap to get N random colors, and then use that as the color argument when you call plt.scatter. color can be a list of colors the same length as the size and population lists, which will color each scatter point separately.

    2. plt.title takes the argument y which will adjust the vertical placement of the title. In your case, try setting it to 1.05.

    Here's your script, modified:

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import numpy as np
    
    N=5
    province=['Ontario','Quebec','BritishColumbia','Manitoba','NovaScoti']
    size = [908.607,1356.547,922.509,552.329,651.036]
    population = [12851821,7903001,4400057,1208268,4160000]
    injuries = [625,752,629,1255,630]
    
    # Choose some random colors
    colors=cm.rainbow(np.random.rand(N))
    
    # Use those colors as the color argument
    plt.scatter(size,population,s=injuries,color=colors)
    for i in range(N):
        plt.annotate(province[i],xy=(size[i],population[i]))
    plt.xlabel('Size(*1000km2)')
    plt.ylabel('Population(ten million)')
    
    # Move title up with the "y" option
    plt.title('The Car Accidents Injuries Rate in 5 Canada Provinces',y=1.05)
    plt.show()
    

    enter image description here