使用matplotlib.pyplot基于CSV

时间:2017-07-11 20:09:30

标签: python matplotlib plot scatter-plot

我想要一个散点图,其中每个点都根据标记着色: 应使用相同的彩色点绘制相同的标签。

eg: tag: 'One', color : red
    tag: 'Two', color : green

输入CSV文件:(第一列是标签)

One;0;0.2345;0.43543;
Two;0.2345;0;0.34563;
One;0.43543;0.34563;0;

绘图代码:

import csv
import numpy as np
import matplotlib.pyplot as plt
from sklearn import manifold
reader = csv.reader(open("data.csv", "r"), delimiter=';')
data = list(reader)

dists = []
tags = []
for d in data:
    tags.append(d[0])
    dists.append(map(float , d[1:-1]))

adist = np.array(dists)
amax = np.amax(adist)
adist /= amax

mds = manifold.MDS(n_components=2, dissimilarity="precomputed", random_state=10)
results = mds.fit(adist)

coords = results.embedding_

plt.subplots_adjust(bottom = 0.1)
plt.scatter(coords[:, 0], coords[:, 1], marker = 'o')
for label, x, y in zip(tags, coords[:, 0], coords[:, 1]):
    plt.annotate(
        label,
        xy = (x, y), xytext = (-8, 8),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.2', fc = 'blue', alpha = 0.1),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

plt.show()

现在显示的所有点都是相同的颜色。 我希望每个点都具有不同的颜色,基于标签的字符串值。 可以从python中的地图中选择颜色

{one:red, two:green, three:yellow}

1 个答案:

答案 0 :(得分:0)

由于您不仅仅需要在代码中进行绘图,因此我建议您对代码进行最少的更改,以便您可以轻松地将其合并:

  • 创建颜色选择的词典:color_dict = {'One':'red', 'Two':'green', 'Three':'yellow'}
  • 通过将plt.scatter()移至for循环并将其更改为plt.scatter(x, y, c=color_dict[label], marker = 'o')
  • 逐个绘制点

完整更新的示例及其结果:

import csv
import numpy as np
import matplotlib.pyplot as plt
from sklearn import manifold
reader = csv.reader(open("data.csv", "r"), delimiter=';')
data = list(reader)

dists = []
tags = []
for d in data:
    tags.append(d[0])
    dists.append(map(float , d[1:-1]))

adist = np.array(dists)
amax = np.amax(adist)
adist /= amax

mds = manifold.MDS(n_components=2, dissimilarity="precomputed", random_state=10)
results = mds.fit(adist)

coords = results.embedding_

color_dict = {'One':'red', 'Two':'green', 'Three':'yellow'}

plt.subplots_adjust(bottom = 0.1)
#plt.scatter(coords[:, 0], coords[:, 1], marker = 'o')
for label, x, y in zip(tags, coords[:, 0], coords[:, 1]):
    plt.scatter(x, y, c=color_dict[label], marker = 'o')
    plt.annotate(
        label,
        xy = (x, y), xytext = (-8, 8),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.2', fc = 'blue', alpha = 0.1),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

plt.show()

enter image description here