【Python知识】可视化函数plt.scatter

这篇具有很好参考价值的文章主要介绍了【Python知识】可视化函数plt.scatter。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

一、说明

二、函数和参数详解

2.1 scatter函数原型

2.2 参数详解

2.3 其中散点的形状参数marker如下:

2.4 其中颜色参数c如下:

三、画图示例

3.1 关于坐标x,y和s,c

3.2 多元高斯的情况

3.3  绘制例子

3.4 绘图例3

3.5  同心绘制

3.6 有标签绘制

3.7 直线划分

3.8 曲线划分


一、说明

       关于matplotlib的scatter函数有许多活动参数,如果不专门注解,是无法掌握精髓的,本文专门针对scatter的参数和调用说起,并配有若干案例。

二、函数和参数详解

2.1 scatter函数原型

matplotlib.pyplot.scatter(xys=Nonec=Nonemarker=Nonecmap=Nonenorm=Nonevmin=Nonevmax=Nonealpha=Nonelinewidths=None*edgecolors=Noneplotnonfinite=Falsedata=None**kwargs)

2.2 参数详解

属性 参数 意义
坐标 x,y 输入点列的数组,长度都是size
点大小 s 点的直径数组,默认直径20,长度最大size
点颜色 c 点的颜色,默认蓝色 'b',也可以是个 RGB 或 RGBA 二维行数组。
点形状 marker 点的样式,默认小圆圈 'o'。
调色板 cmap

Colormap,默认 None,标量或者是一个 colormap 的名字,只有 c 是一个浮点数数组时才使用。如果没有申明就是 image.cmap。

亮度(1) norm Normalize,默认 None,数据亮度在 0-1 之间,只有 c 是一个浮点数的数组的时才使用。
亮度(2) vmin,vmax 亮度设置,在 norm 参数存在时会忽略。
透明度 alpha 透明度设置,0-1 之间,默认 None,即不透明
线 linewidths  标记点的长度
颜色

edgecolors

颜色或颜色序列,默认为 'face',可选值有 'face', 'none', None。

plotnonfinite

布尔值,设置是否使用非限定的 c ( inf, -inf 或 nan) 绘制点。

**kwargs 

其他参数。

2.3 其中散点的形状参数marker如下:

【Python知识】可视化函数plt.scatter

【Python知识】可视化函数plt.scatter

2.4 其中颜色参数c如下:

【Python知识】可视化函数plt.scatter

三、画图示例

3.1 关于坐标x,y和s,c

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)


N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)          # 颜色可以随机
area = (30 * np.random.rand(N))**2  # 点的宽度30,半径15

plt.scatter(x, y, s=area, c=colors, alpha=0.5)  
plt.show()

【Python知识】可视化函数plt.scatter

        注意:以上核心语句是:

plt.scatter(x, y, s=area, c=colors, alpha=0.5, marker=",")

        其中:x,y,s,c维度一样就能成。

3.2 多元高斯的情况

​
import numpy as np
import matplotlib.pyplot as plt


fig=plt.figure(figsize=(8,6))
#Generating a Gaussion dataset:
#creating random vectors from the multivariate normal distribution
#given mean and covariance
mu_vec1=np.array([0,0])
cov_mat1=np.array([[1,0],[0,1]])
X=np.random.multivariate_normal(mu_vec1,cov_mat1,500)
R=X**2
R_sum=R.sum(axis=1)
plt.scatter(X[:,0],X[:,1],color='green',marker='o', =32.*R_sum,edgecolor='black',alpha=0.5)

plt.show()

​

【Python知识】可视化函数plt.scatter

3.3  绘制例子

from matplotlib import pyplot as plt
import numpy as np
# Generating a Gaussion dTset:
#Creating random vectors from the multivaritate normal distribution
#givem mean and covariance

mu_vecl = np.array([0, 0])
cov_matl = np.array([[2,0],[0,2]])

x1_samples = np.random.multivariate_normal(mu_vecl, cov_matl,100)
x2_samples = np.random.multivariate_normal(mu_vecl+0.2, cov_matl +0.2, 100)
x3_samples = np.random.multivariate_normal(mu_vecl+0.4, cov_matl +0.4, 100)

plt.figure(figsize = (8, 6))

plt.scatter(x1_samples[:,0], x1_samples[:, 1], marker='x',
           color = 'blue', alpha=0.7, label = 'x1 samples')
plt.scatter(x2_samples[:,0], x1_samples[:,1], marker='o',
           color ='green', alpha=0.7, label = 'x2 samples')
plt.scatter(x3_samples[:,0], x1_samples[:,1], marker='^',
           color ='red', alpha=0.7, label = 'x3 samples')
plt.title('Basic scatter plot')
plt.ylabel('variable X')
plt.xlabel('Variable Y')
plt.legend(loc = 'upper right')

plt.show()


    import matplotlib.pyplot as plt
    
    fig,ax = plt.subplots()
    
    ax.plot([0],[0], marker="o",  markersize=10)
    ax.plot([0.07,0.93],[0,0],    linewidth=10)
    ax.scatter([1],[0],           s=100)
    
    ax.plot([0],[1], marker="o",  markersize=22)
    ax.plot([0.14,0.86],[1,1],    linewidth=22)
    ax.scatter([1],[1],           s=22**2)
    
    plt.show()



![image.png](http://upload-images.jianshu.io/upload_images/8730384-8d27a5015b37ee97.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    import matplotlib.pyplot as plt
    
    for dpi in [72,100,144]:
    
        fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
        ax.set_title("fig.dpi={}".format(dpi))
    
        ax.set_ylim(-3,3)
        ax.set_xlim(-2,2)
    
        ax.scatter([0],[1], s=10**2, 
                   marker="s", linewidth=0, label="100 points^2")
        ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
                   marker="s", linewidth=0, label="100 pixels^2")
    
        ax.legend(loc=8,framealpha=1, fontsize=8)
    
        fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")
    
    plt.show() 

【Python知识】可视化函数plt.scatter

3.4 绘图例3

import matplotlib.pyplot as plt

for dpi in [72,100,144]:

    fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
    ax.set_title("fig.dpi={}".format(dpi))

    ax.set_ylim(-3,3)
    ax.set_xlim(-2,2)

    ax.scatter([0],[1], s=10**2, 
               marker="s", linewidth=0, label="100 points^2")
    ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
               marker="s", linewidth=0, label="100 pixels^2")

    ax.legend(loc=8,framealpha=1, fontsize=8)

    fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")

plt.show() 

【Python知识】可视化函数plt.scatter

3.5  同心绘制

plt.scatter(2, 1, s=4000, c='r')
plt.scatter(2, 1, s=1000 ,c='b')
plt.scatter(2, 1, s=10, c='g')

【Python知识】可视化函数plt.scatter

3.6 有标签绘制

import matplotlib.pyplot as plt

x_coords = [0.13, 0.22, 0.39, 0.59, 0.68, 0.74,0.93]
y_coords = [0.75, 0.34, 0.44, 0.52, 0.80, 0.25,0.55]

fig = plt.figure(figsize = (8,5))

plt.scatter(x_coords, y_coords, marker = 's', s = 50)
for x, y in zip(x_coords, y_coords):
    plt.annotate('(%s,%s)'%(x,y), xy=(x,y),xytext = (0, -10), textcoords = 'offset points',ha = 'center', va = 'top')
plt.xlim([0,1])
plt.ylim([0,1])
plt.show()

【Python知识】可视化函数plt.scatter

3.7 直线划分

# 2-category classfication with random 2D-sample data
# from a multivariate normal distribution

import numpy as np
from matplotlib import pyplot as plt

def decision_boundary(x_1):
    """Calculates the x_2 value for plotting the decision boundary."""
#    return 4 - np.sqrt(-x_1**2 + 4*x_1 + 6 + np.log(16))
    return -x_1 + 1

# Generating a gaussion dataset:
# creating random vectors from the multivariate normal distribution
# given mean and covariance

mu_vec1 = np.array([0,0])
cov_mat1 = np.array([[2,0],[0,2]])
x1_samples = np.random.multivariate_normal(mu_vec1, cov_mat1,100)
mu_vec1 = mu_vec1.reshape(1,2).T # TO 1-COL VECTOR

mu_vec2 = np.array([1,2])
cov_mat2 = np.array([[1,0],[0,1]])
x2_samples = np.random.multivariate_normal(mu_vec2, cov_mat2, 100)
mu_vec2 = mu_vec2.reshape(1,2).T # to 2-col vector

# Main scatter plot and plot annotation

f, ax = plt.subplots(figsize = (7, 7))
ax.scatter(x1_samples[:, 0], x1_samples[:,1], marker = 'o',color = 'green', s=40)
ax.scatter(x2_samples[:, 0], x2_samples[:,1], marker = '^',color = 'blue', s =40)
plt.legend(['Class1 (w1)', 'Class2 (w2)'], loc = 'upper right')
plt.title('Densities of 2 classes with 25 bivariate random patterns each')
plt.ylabel('x2')
plt.xlabel('x1')
ftext = 'p(x|w1) -N(mu1=(0,0)^t, cov1 = I)\np.(x|w2) -N(mu2 = (1, 1)^t), cov2 =I'
plt.figtext(.15,.8, ftext, fontsize = 11, ha ='left')

#Adding decision boundary to plot

x_1 = np.arange(-5, 5, 0.1)
bound = decision_boundary(x_1)
plt.plot(x_1, bound, 'r--', lw = 3)

x_vec = np.linspace(*ax.get_xlim())
x_1 = np.arange(0, 100, 0.05)

plt.show()

【Python知识】可视化函数plt.scatter

3.8 曲线划分

# 2-category classfication with random 2D-sample data
# from a multivariate normal distribution

import numpy as np
from matplotlib import pyplot as plt

def decision_boundary(x_1):
    """Calculates the x_2 value for plotting the decision boundary."""
    return 4 - np.sqrt(-x_1**2 + 4*x_1 + 6 + np.log(16))

# Generating a gaussion dataset:
# creating random vectors from the multivariate normal distribution
# given mean and covariance

mu_vec1 = np.array([0,0])
cov_mat1 = np.array([[2,0],[0,2]])
x1_samples = np.random.multivariate_normal(mu_vec1, cov_mat1,100)
mu_vec1 = mu_vec1.reshape(1,2).T # TO 1-COL VECTOR

mu_vec2 = np.array([1,2])
cov_mat2 = np.array([[1,0],[0,1]])
x2_samples = np.random.multivariate_normal(mu_vec2, cov_mat2, 100)
mu_vec2 = mu_vec2.reshape(1,2).T # to 2-col vector

# Main scatter plot and plot annotation

f, ax = plt.subplots(figsize = (7, 7))
ax.scatter(x1_samples[:, 0], x1_samples[:,1], marker = 'o',color = 'green', s=40)
ax.scatter(x2_samples[:, 0], x2_samples[:,1], marker = '^',color = 'blue', s =40)
plt.legend(['Class1 (w1)', 'Class2 (w2)'], loc = 'upper right')
plt.title('Densities of 2 classes with 25 bivariate random patterns each')
plt.ylabel('x2')
plt.xlabel('x1')
ftext = 'p(x|w1) -N(mu1=(0,0)^t, cov1 = I)\np.(x|w2) -N(mu2 = (1, 1)^t), cov2 =I'
plt.figtext(.15,.8, ftext, fontsize = 11, ha ='left')

#Adding decision boundary to plot

x_1 = np.arange(-5, 5, 0.1)
bound = decision_boundary(x_1)
plt.plot(x_1, bound, 'r--', lw = 3)

x_vec = np.linspace(*ax.get_xlim())
x_1 = np.arange(0, 100, 0.05)

plt.show()

【Python知识】可视化函数plt.scatter文章来源地址https://www.toymoban.com/news/detail-490419.html

到了这里,关于【Python知识】可视化函数plt.scatter的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 知识图谱的构建及可视化

    知识图谱 Knowledge Graph/Vault ,又称科学知识图谱,用各种不同的图形等可视化技术描述知识资源及其载体,挖掘、分析、构建、绘制和显示知识及它们之间的相互联系。采用图结构来描述知识,建模事物及事物间关系。提供了一种组织、管理和认知理解海量信息的能力。 其本

    2024年01月18日
    浏览(13)
  • 概率密度函数可视化

    1 一维随机变量情形 以正态概率密度函数为例,其中位置参数为 μ mu μ ,尺度参数为 σ sigma σ , f ( x ) = 1 2 π σ e − ( x − μ ) 2 2 σ 2 , x ∈ R f(x) = dfrac{1}{sqrt{2pi}sigma}e^{-dfrac{(x-mu)^2}{2sigma^2}},xin R f ( x ) = 2 π ​ σ 1 ​ e − 2 σ 2 ( x − μ ) 2 ​ , x ∈ R 2 二维随机变量情形

    2024年02月06日
    浏览(15)
  • 知识图谱实战应用1-知识图谱的构建与可视化应用

    大家好,今天给大家带来知识图谱实战应用1-知识图谱的构建与可视化应用。知识图谱是一种概念模型,用于表示和组织实体之间的关系,从而实现大规模的语义查询和推理。 一、知识图谱的应用领域 1. 搜索引擎 :知识图谱可以帮助搜索引擎更好地理解用户的搜索查询,提

    2024年02月10日
    浏览(13)
  • 大型语言模型基础知识的可视化指南

    如今,LLM(大型语言模型的缩写)在全世界都很流行。没有一天不在宣布新的语言模型,这加剧了人们对错过人工智能领域的恐惧。然而,许多人仍在为 LLM 的基本概念而苦苦挣扎,这使他们难以跟上时代的进步。本文的目标读者是那些希望深入了解此类人工智能模型的内部

    2024年01月24日
    浏览(20)
  • 7个Pandas绘图函数助力数据可视化

    大家好,在使用Pandas分析数据时,会使用Pandas函数来过滤和转换列,连接多个数据帧中的数据等操作。但是,生成图表将数据在数据帧中可视化 , 通常比仅仅查看数字更有帮助。 Pandas具有几个绘图函数,可以使用它们快速轻松地实现数据可视化,文中将介绍这些函数。 首先

    2024年01月21日
    浏览(21)
  • GeoServer中地图可视化提升利器之SLD知识简介

    目录 前言  一、SLD简介 1、介绍 2、SLD的版本 3、SLD的Schema说明 二、SLD中相关知识解析 1、Scheme简要说明 2、一个SLD实例 总结         在互联网上有很多精美的地图,在地图从shp或者gdb等矢量文件,经过设计人员的加工,配色,标注,符号化等等修饰加工。原始的点线面数

    2024年02月09日
    浏览(20)
  • pandas plot函数:数据可视化的快捷通道

    一般来说,我们先用 pandas 分析数据,然后用 matplotlib 之类的可视化库来显示分析结果。 而 pandas 库中有一个强大的工具-- plot 函数,可以使数据可视化变得简单而高效。 plot 函数是 pandas 中用于数据可视化的一个重要工具, 通过 plot 函数,可以轻松地将 DataFrame 或 Series 对象

    2024年03月09日
    浏览(18)
  • 毕业设计:基于知识图谱的《红楼梦》人物关系可视化

    项目介绍 github 地址:https://github.com/chizhu/KGQA_HLM?tab=readme-ov-file 基于知识图谱的《红楼梦》人物关系可视化:应该是重庆邮电大学林智敏同学的毕业设计,在学习知识图谱的过程中参考使用。 文件树: app.py 是整个系统的主入口 templates 文件夹是 HTML 的页面 |- index.html 欢迎界面

    2024年02月21日
    浏览(17)
  • MATLAB数学建模:数据图形可视化-三维绘图函数

    在 MATLAB 中, 我们可使用函数 surf 和 surfc 绘制三维曲面图. 调用格式如下: 以矩阵 ZZZ 所指定的参数创建一个渐变的三维曲面. 坐标 $x = 1:n, y = 1:m, $ 其中 [m,n]=size(Z)[m,n] = size(Z)[m,n]=size(Z) 以 ZZZ 确定的曲面高度和颜色, 按照 X,YX,YX,Y 形成的格点矩阵, 创建一个渐变的三维曲面. X,

    2024年02月06日
    浏览(23)
  • 【数字孪生百科】可视化图表知识科普——Pareto图(Pareto Chart)

    Pareto图 (Pareto Chart)又称 帕累托图 、 排列图 ,是一种特殊类型的 条形图 。图中标绘的值是按照事件发生的频率排序而成,显示由于各种原因引起的缺陷数量或不一致的排列顺序。Pareto图是根据 Vilfredo Pareto 命名的,他的原理是“二八原则”,即20%的原因造成80%的问题,如

    2024年02月12日
    浏览(16)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包