Reputation: 35
In the following bubble chart, how can I:
Randomize the color of each bubble
Adjust the title (maybe upper) so it will not overlap with the graph tag on the far up left corner.
Here is my output:
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
Upvotes: 2
Views: 5892
Reputation: 69126
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.
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()
Upvotes: 5
Reputation: 383
1) For the colours I found this answer with 3 solutions one of which is:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
plt.scatter(x, y, color=c)
2) For the title overlap, you can remove the overlap by resizing the window. You can set the window size (check set_size_inches
).
Upvotes: 0