I am reading this website and found this line of code:
for i in centroids.keys():
plt.scatter(*centroids[i], color=colmap[i])
I understand *
is used to gather an arbitrary length of arguments so we don't have to explicitly specify all the arguments, right?
But why does this person write the *
here?
Especially since after removing the *
, the line seem to produce the same result.
The complete code:
## Initialisation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.DataFrame({
'x': [12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 52, 55, 53, 55, 61, 64, 69, 72],
'y': [39, 36, 30, 52, 54, 46, 55, 59, 63, 70, 66, 63, 58, 23, 14, 8, 19, 7, 24]
})
np.random.seed(200)
k = 3
# centroids[i] = [x, y]
centroids = {
i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
for i in range(k)
}
fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'], df['y'], color='k')
colmap = {1: 'r', 2: 'g', 3: 'b'}
for i in centroids.keys():
plt.scatter(*centroids[i], color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show()
Axes.scatter(x, y, ...)
takes two arguments x and y.
When removing the asterix you have one single argument only, hence plt.scatter(centroids[i], color=colmap[i])
should throw a TypeError: scatter() takes at least 2 arguments (1 given)
.
The alternative would be to split the argument beforehands,
x,y = centroids[i]
plt.scatter(x,y, color=colmap[i])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.