首页 > 解决方案 > 如何根据文本字段设置散点图的标记颜色?

问题描述

我有一个 2d python 列表,其中每一行都有 ax、y、z 值,但我的 z 值是文本,它只包含两个值之一,“br”或“comp”

我想制作一个使用 x,y 值的散点图,然后将 z 值显示为基于文本的颜色。这是我的数组的样子:

| x     | y     | z     |

|---    |-----  |------ |

| 1     | 1.2   | br    |

| 2     | 4.3   | comp  |

| 3     | 4.5   | comp  |

| 4     | 6.7   | br    |

我试图看看它是否会识别并根据字段值创建两个单独的类,但是唉,我得到了一个 ValueError:

ValueError: 'c' argument must be a mpl color, a sequence of mpl colors or a sequence of numbers, not ['br', 'comp', etc]

这是我的绘图代码的样子:


fig, axs = plt.subplots(nrows = 4, ncols = 2, sharex = True, sharey = True, figsize = (20,20))
axs = axs.flatten()
for j in range(len(devs)):
    axs[j].scatter([i[2] for i in devs[j]], [i[4] for i in devs[j]], c = [i[3] for i in devs[j]])
plt.show()

devs是 2d python 列表的列表。我的 x 值在第三列,y 值在第 5 列,z 值在我的第 4 列,因此是复杂的散点图代码行。

我的预期结果是带有两个不同颜色标记的 x,y 散点图,一种颜色对应于 z 值“comp”的行,另一种颜色对应于 z 值“br”的行。

提前致谢!

标签: pythonmatplotlibcolorsscatter

解决方案


您可以使用字典来保存颜色名称。试试下面的代码,看看天气如何。

dic =  {
  "br": "red",
  "comp": "green"
}

fig, axs = plt.subplots(nrows = 4, ncols = 2, sharex = True, sharey = True, figsize = (20,20))
axs = axs.flatten()
for j in range(5):
    axs[j].scatter([i[2] for i in devs[j]], [i[4] for i in devs[j]], c = [dic[str(i[3])] for i in devs[j]])
plt.show()

推荐阅读