使用字符串着色的Pandas散点图

9o685dep  于 2023-06-04  发布在  其他
关注(0)|答案(2)|浏览(385)

我想用散点图绘制x和y,z作为颜色。

import pandas as pd

df = pd.DataFrame({
    "x": [1,2 ,3],
    "y": [4, 5, 6],
    "z": ["A", "B", "C"],
})

df.plot(
    x="x",
    y="y",
    kind="scatter",
    c="z",
)

我如何使用pandas绘图功能来实现这一点?
这是投掷:

ValueError: 'c' argument must be a color, a sequence of colors, or a sequence of numbers, not ['A' 'B' 'C']
y0u0uwnf

y0u0uwnf1#

要根据分类变量'z'用不同颜色绘制散点图,可以使用字典将'z'的每个唯一值Map到特定颜色,然后将Map的颜色作为'c'参数传递:

df = pd.DataFrame({
    "x": [1, 2, 3],
    "y": [4, 5, 6],
    "z": ["A", "B", "C"],
})

color_map = {"A": "red", "B": "green", "C": "blue"}

df.plot(
    x="x",
    y="y",
    kind="scatter",
    c=df['z'].map(color_map),
    colormap='viridis',
)

plt.show()
myzjeezk

myzjeezk2#

你可以简单地在'z'中添加一些颜色

import pandas as pd

df = pd.DataFrame({
    "x": [1,2 ,3],
    "y": [4, 5, 6],
    "z": ["red", "blue", "green"],
})

df.plot(
    x="x",
    y="y",
    kind="scatter",
    c="z",
)

相关问题