文章地址:https://www.chzzz.club/post/239.html
我们在使用聚类算法时,希望最后画出的散点图中,不同的类别的点拥有不同的颜色和不同的形状的,但是matplotlib只能让我们使不同类别拥有不同的颜色,而对形状无能为力。下面这段代码就可以实现这个功能:
import numpy as np
import matplotlib.pyplot as plt
def mscatter(x,y,ax=None, m=None, **kw):
import matplotlib.markers as mmarkers
if not ax: ax=plt.gca()
sc = ax.scatter(x,y,**kw)
if (m is not None) and (len(m)==len(x)):
paths = []
for marker in m:
if isinstance(marker, mmarkers.MarkerStyle):
marker_obj = marker
else:
marker_obj = mmarkers.MarkerStyle(marker)
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
paths.append(path)
sc.set_paths(paths)
return sc
N = 8#假设有8个点
x=[1,2,3,4,5,6,7,8]
y=[1,2,3,4,5,6,7,8]
c=[1,2,2,2,3,3,4,4]#有4个类别,标签分别是1,2,3,4
m = {1:'o',2:'s',3:'D',4:'+'}
cm = list(map(lambda x:m[x],c))#将相应的标签改为对应的marker
print(cm)
fig, ax = plt.subplots()
scatter = mscatter(x, y, c=c, m=cm, ax=ax,cmap=plt.cm.RdYlBu)
plt.show()
假设有8个点,[(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),(8,8)],他们的标签分别是(1,2,2,2,3,3,4,4),
得到的结果:
参考:
https://stackoverflow.com/questions/52303660/iterating-markers-in-plots/52303895#52303895
https://github.com/matplotlib/matplotlib/issues/11155
附录:
散点的形状参数marker: