gpt4 book ai didi

字典中的 Matplotlib 散点图标记类型

转载 作者:行者123 更新时间:2023-12-05 02:36:45 24 4
gpt4 key购买 nike

用Matplotlib画散点图(不是Seaborn、Pandas等高级接口(interface)),如何用字典指定标记类型?

此示例使用颜色字典:

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),
)

enter image description here

但是以下抛出错误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 似乎不支持多个标记。 @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")

enter image description here

关于字典中的 Matplotlib 散点图标记类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70191327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com