如何通过字典指定Matplotlib原生散点图的marker标记类型
问题原因
matplotlib 的 scatter() 方法的 marker 参数仅支持传入单个标记类型,不支持像颜色参数那样传入逐点配置的序列,所以直接传入映射后的 Series 会触发类型错误。
解决方案
方法1:按类别分批次调用scatter(原生接口推荐)
该方案完全不需要依赖 Pandas、Seaborn 等高阶封装,仅用 Matplotlib 原生接口即可实现,遍历不同的类别,每次只绘制同一类别的散点,单独指定该类对应的 marker 和颜色即可:
import matplotlib.pyplot as plt # 原始数据,无需DataFrame存储 x = [4, 8, 1, 0, 2] y = [0.1, 1, 0.4, 0.8, 0.9] name = ["A", "A", "B", "A", "B"] # 配置映射规则 colors = {"A": "red", "B": "blue"} markers = {"A": "v", "B": "D"} fig, ax = plt.subplots(1, 1) # 按类别遍历绘制 for cls in colors.keys(): # 筛选当前类别的坐标点 cls_x = [x[i] for i in range(len(x)) if name[i] == cls] cls_y = [y[i] for i in range(len(y)) if name[i] == cls] ax.scatter( x=cls_x, y=cls_y, facecolors="none", edgecolors=colors[cls], marker=markers[cls] ) plt.show()
方法2:配合Pandas分组实现(若已使用DataFrame存储数据)
如果你已经在用 DataFrame 存储数据,也可以用分组逻辑实现,本质和方法1逻辑一致:
import matplotlib.pyplot as plt import pandas as pd x = [4, 8, 1, 0, 2] y = [0.1, 1, 0.4, 0.8, 0.9] name = ["A", "A", "B", "A", "B"] df = pd.DataFrame(data=zip(x, y, name), columns=["x", "y", "name"]) colors = {"A": "red", "B": "blue"} markers = {"A": "v", "B": "D"} fig, ax = plt.subplots(1, 1) for cls, group in df.groupby("name"): ax.scatter( x=group["x"], y=group["y"], facecolors="none", edgecolors=colors[cls], marker=markers[cls] ) plt.show()
内容的提问来源于stack exchange,提问作者a11
相关产品推荐
相关产品推荐

