我猜您想要的颜色分离来自数据框中的分类列。我会解决它以遍历切片数据帧:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'x':[1,1,2,3,4],'y':[2,4,3,7,5],
'weight':[2,4,8,5,6],'catnum':[2,3,5,1,7],
'catc':['car','car','bike','bike','truck']})
# regular example without categorical:
fig1, ax1 = plt.subplots()
size = 5 * df['weight'].to_numpy()**2
ax1.scatter(df.x,df.y,c=df.catnum,s=size)
fig1.suptitle('numerical demo')
plt.show()
# function to iterate through your categorical column
def _getItr(data,key):
kinds = sorted(data[key].unique())
itr = {}
for i in range(len(kinds)):
itr[i]=data[data[key]==kinds[i]]
return itr, kinds
cf, cats = _getItr(df,'catc')
fig2, ax2 = plt.subplots()
for c in cf:
ax2.scatter(cf[c]['x'],cf[c]['y'],s=(5 * cf[c]['weight'].to_numpy()**2),label=cats[c])
legend2 = ax2.legend()
for h in legend2.legendHandles: h.set_sizes([30.0]) # otherwize markers in legend have different size
fig2.suptitle('colors and legend from categorical')
plt.show()
example fig2