【问题标题】:Multi color scatter plot using matplotlib.pyplot based on input field from CSV基于 CSV 输入字段使用 matplotlib.pyplot 的多色散点图
【发布时间】:2017-07-11 20:09:30
【问题描述】:

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

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}

【问题讨论】:

  • 您的问题/问题不是很明显?
  • 我已经编辑了这个问题,希望这会让我的问题更清楚

标签: python matplotlib plot scatter-plot


【解决方案1】:

由于您不仅仅是在代码中绘制,我将建议一个对您的代码进行最少更改的解决方案,以便您可以轻松地合并它:

  • 为颜色选择创建一个字典: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()

【讨论】:

    猜你喜欢
    • 2015-09-27
    • 2013-06-26
    • 2018-10-02
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    相关资源
    最近更新 更多