【问题标题】:How to create a scatter plot with two colors per dot?如何创建每个点有两种颜色的散点图?
【发布时间】:2020-01-19 13:46:08
【问题描述】:

我正在尝试在 matplotlib 中同时绘制 ground-truthmy 分类。

目前,在特征空间上应用tsne 并使用以下代码添加边之后,我只绘制了真实情况

from matplotlib.collections import LineCollection
cols=['rgbkm'[lbl] for lbl in list(data.y.cpu().numpy() - 1)]

lc = LineCollection(X_embedded[out_dict['edges']],linewidth=0.05)
fig = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(X_embedded[:,0].min(), X_embedded[:,0].max())
plt.ylim(X_embedded[:,1].min(), X_embedded[:,1].max())
plt.scatter(X_embedded[:,0],X_embedded[:,1], c=cols)

这给出了以下情节:

同时,我希望通过以下方式为每个顶点着色:

【问题讨论】:

  • 您希望每个点都恰好是半红半蓝,并且与您显示的方向相同?还是颜色的任何部分取决于某个变量?
  • ground-truth 和我的分类同时进行,这意味着我希望它们由一些变量设置
  • 而变量会对应什么?标记中有多少是红色的,有多少是蓝色的?每一半的颜色(即 alpha 值,或不同的阴影)?
  • 不,我将为每个顶点提供两个分类,例如例如,1-3 对应黑色/红色,或 3-5 对应红色/蓝色,例如

标签: python matplotlib scatter-plot


【解决方案1】:

这里有两种方法。

常规散点图的点可以有内部颜色和边缘颜色。 scatter 接受其中任何一个的数组,但不接受两者。因此,您可以遍历所有边缘颜色并将它们绘制在同一图上的循环中。 使用线宽可能有助于将真实颜色和预测颜色一起可视化。

Matplotlib 的 plot 函数接受标记 filling styles,它有可能是双色的,无论是上下还是左右。每个情节你只能给出一种风格。因此,对于 5 种颜色,可以循环绘制 25 种组合。

奖励积分:

在循环颜色时,绘图可以生成带有相应双色点的图例标签。

这里有一些代码来说明这些概念:

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

N = 50

labels = ['ant', 'bee', 'cat', 'dog', 'elk']  # suppose these are the labels for the prediction
colors = list('rgbkm') # a list of 5 colors
cols_true = np.repeat(range(5), N)  # suppose the first N have true color 0, the next N true color 1, ...
cols_pred = np.random.randint(0, 5, N * 5)  # as a demo, take a random number for each predicted color

# for x and y, suppose some 2D gaussian normal distribution around some centers,
#   this would make the 'true' colors nicely grouped 
x = np.concatenate([np.random.normal(cx, 2, N) for cx in [5, 9, 7, 2, 2]])
y = np.concatenate([np.random.normal(cy, 1.5, N) for cy in [2, 5, 9, 8, 3]])

fig, ax = plt.subplots(figsize=(10,6))
for tc in range(5):
    for pc in range(5):
        mask = (cols_true == tc) & (cols_pred == pc)
        plt.plot(x[mask], y[mask], c=colors[tc], markerfacecoloralt=colors[pc],
                 marker='.', linestyle='', markeredgecolor='None',
                 markersize=15, fillstyle='left', markeredgewidth=0,
                 label=f'Tr: {labels[tc]} - Pr: {labels[pc]}')
plt.legend(loc='upper right', bbox_to_anchor=(1, -0.1), fontsize=10, ncol=5)
plt.tight_layout()
plt.show()

【讨论】:

  • 哇,我认为它无法完成,并在您的帖子之前使用了边缘方案(正如您也提到的)。惊人的
猜你喜欢
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 2019-09-28
  • 2016-01-22
  • 1970-01-01
相关资源
最近更新 更多