我有一个包含3列的数据文件。前两列代表坐标,第三列是字符串值,如'foo','bar'或'ter'。
我想用python的matplotlib显示基于这个标签,不同的标记和颜色。例如:
到目前为止我所做的是:
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()
答案 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)