【问题标题】:Matplotlib scatter plot marker type from dictionary字典中的 Matplotlib 散点图标记类型
【发布时间】:2021-12-01 21:18:07
【问题描述】:

使用 Matplotlib 制作散点图(不是 Seaborn、Pandas 或其他高级接口),如何使用字典指定标记类型?

此示例适用于颜色字典:

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"}

fig, ax = plt.subplots(1, 1)
ax.scatter(
    x=df["x"],
    y=df["y"],
    facecolors="none",
    edgecolors=df["name"].map(colors),
)

但是下面会抛出错误TypeError: 'Series' objects are mutable, thus they cannot be hashed:

markers = {"A": "v", "B": "D"}

fig, ax = plt.subplots(1, 1)
ax.scatter(
    x=df["x"],
    y=df["y"],
    facecolors="none",
    edgecolors=df["name"].map(colors),
    marker=df['name'].map(markers),
)

【问题讨论】:

  • @BigBen 哇,这仍然是真的吗?链接的帖子已经有几年了,matplotlib 还不支持多个标记吗?
  • 来自docs:标记样式。标记可以是类的实例,也可以是特定标记的文本速记。 Matplotlib 不支持在一个分散调用中使用多个标记。一种选择是循环,演示here

标签: matplotlib scatter


【解决方案1】:

根据@BigBen 的 cmets,看起来 Matplotlib 不支持多个标记。 @BigBen 链接到几个示例解决方法,但我发现以下方法最适合我,因为它允许我在代码开头明确地将关键字与标记样式相关联,而不管 df 的哪个子集我我正在与。 (现实生活中的数据有十几个“名称”值,我正在处理基于其他列中的属性的各种混合子集。)

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 name, group in df.groupby("name"):
    group = group.copy()
    m = markers.get(name)

    ax.scatter(
        x=group["x"],
        y=group["y"],
        facecolors="none",
        edgecolors=group["name"].map(colors),
        marker=m,
        label=name,
    )
    ax.legend(loc="lower right")

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多