如何在matplotlib中更改特定列值的标记和颜色?

时间:2016-04-16 16:19:49

标签: python matplotlib

我有一个包含3列的数据文件。前两列代表坐标,第三列是字符串值,如'foo','bar'或'ter'。

我想用python的matplotlib显示基于这个标签,不同的标记和颜色。例如:

  • foo =>红圈
  • bar =>绿色三角形
  • ter =>黑色方块

到目前为止我所做的是:

import numpy as np
import matplotlib.pyplot as plt

coordData = np.genfromtxt("mydata.csv", usecols=(0,1), delimiter=",", dtype=None)
coordLabels = np.genfromtxt("mydata.csv", usecols=2, delimiter=",", dtype=None)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(coordData[:, 0], coordData[:, 1], c="r", marker="o") 
plt.show()

如何根据coordLabels值切换标记和颜色?

基于这个建议我做了一些改变:

coordData = np.genfromtxt("mydata.csv", usecols=(0, 1), delimiter=",", dtype=None)
coordLabels = np.genfromtxt("mydata.csv", usecols=2, delimiter=",", dtype=None)

fig = plt.figure()
ax = fig.add_subplot(111)

uniqueVals = np.unique(coordLabels)

markers = ['^', 'o', '*']
colors = { '^' : 'r',
           'o' : 'b',
           '*' : 'g'}

for marker, val in zip(markers, uniqueVals):
    toUse = coordLabels == val
    ax.scatter(coordData[toUse,0], coordData[toUse,1], c = colors[marker], marker=marker)

plt.show()

1 个答案:

答案 0 :(得分:1)

如果您希望颜色取决于coordLabels中的标签,您希望将颜色设置为 变量,而不是像'r'那样。< / p>

ax.scatter(coordData[:, 0], coordData[:, 1], c=coordLabels, marker="o") 

如果您需要为每个图表添加不同的标记,则需要创建多个散点图(coordLabels

中的每个值一个)
uniqueVals = ['foo', 'bar', 'ter']

# Create your own list of markers here (needs to be the same size as `uniqueVals`)
markers = ['o', '^', 's']
colors = ['r', 'g', 'b']

for color, marker, val in zip(colors, markers, uniqueVals):
    toUse = coordLabels == val
    ax.scatter(coordData[toUse,0], coordData[toUse,1], c=color, marker=marker)