python画散点图

问题描述

总结一个普遍的画图格式太难了,我就举一个比较复杂的例子来说明,比如我有一个嵌入向量矩阵(N*128),想将其可视化到二维平面,所以就用t-sne将其降维并画出散点图。该嵌入向量表示的点有两类,并且希望不同类别的点在散点图上具有不同的大小、形状、颜色和透明度。

实例

数据准备

  1. 有一个(N**2)的数组(ndarray/list),和一个N*1的list来说明每个点的类型
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
'''
把高维数据通过t-sne降维成二维的数据
'''
addr = r"addr"
embedding_addr = addr + r"\embedding.txt"
label_addr = addr + r"\label.txt"
embedding = np.loadtxt(embedding_addr) #N*128
label = np.loadtxt(label_addr) #N
newX = TSNE(n_components=2,random_state=33).fit_transform(embedding)#(N*2)

  • 将其根据类型拆分成两个数据集data1,data2
type1_x = []
type1_y = []
type2_x = []
type2_y = []
for i in range(len(label)-8700):#为了图清晰一些,故意删去了一些点
    #if i not in test_dataset_index:
    if label[i]==0:
        type1_x.append(newX[i][0])
        type1_y.append(newX[i][1])
    if label[i]==1:
        type2_x.append(newX[i][0])
        type2_y.append(newX[i][1])
#转化为ndarray类型
type1_x = np.array(type1_x)
type1_y = np.array(type1_y)
type2_x = np.array(type2_x)
type2_y = np.array(type2_y)
#data1,data2 分别是 N1*2N2*2
data1 = np.column_stack((type1_x,type1_y)) #把x坐标和y坐标拼接起来
data2 = np.column_stack((type2_x,type2_y)) #把x坐标和y坐标拼接起来
  • 设置两种数据集描述的点在散点图中的特点,比如颜色、大小以及形状
type1_color = 'green'
type2_color = 'red'
type1_size = 20
type2_size = 40
type1_marker = 's'
type2_marker = 'p'
type1_transparent = 0.3
type2_transparent = 1
  • 其中color的可选项有(简写和全拼都可)
    ‘b‘= blue(蓝色)
    ‘g’=green(绿色)
    ‘r’=red(红色)
    ‘c’=cyan(青色)
    ‘m’=magenta(品红)
    ‘y’=yellow(黄色)
    ‘k’=black(黑色)
    ‘w’=white(白色)
  • 大小size的默认值是20,可调
  • 其中形状的可选项有
    在这里插入图片描述
  • 透明度是从0~1
  1. DataFrame这两个数据集
df1 = pd.DataFrame(data1, columns=['x','y'])
df2 = pd.DataFrame(data2, columns=['x','y'])

绘制散点图

'''
每一类数据依次在图上画出来
kind = scatter 意为散点图
x,y是指横纵坐标
c = color
s = size
label 图注
'''
ax = df1.plot(kind='scatter', x='x', y='y', c=type1_color,s=type1_size, marker=type1_marker,alpha=type1_transparent,label="type1")
df2.plot(kind='scatter', x='x', y='y', c=type2_color,s=type2_size, marker=type2_marker,alpha=type2_transparent,ax=ax,label="type2")#两个类别依次画在图上

plt.show()

结果展示

结果展示

参考

  1. https://blog.csdn.net/qq_40949544/article/details/88222538
  2. https://www.gairuo.com/p/pandas-plot-scatter
  3. https://www.cnblogs.com/shanger/p/12925703.html
  4. https://blog.csdn.net/h_hxx/article/details/90635650
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值