Python绘制散点图的教程详解

 更新时间:2022年03月16日 15:23:02   作者:Vertira  
散点图是指在回归分析中,数据点在直角坐标系平面上的分布图,散点图表示因变量随自变量而变化的大致趋势,据此可以选择合适的函数对数据点进行拟合。本文将用Python绘制散点图,需要的可以参考一下

少废话,直接上代码 

import matplotlib.pyplot as plt
import numpy as np
# 1. 首先是导入包,创建数据
n = 10
x = np.random.rand(n) * 2# 随机产生10个0~2之间的x坐标
y = np.random.rand(n) * 2# 随机产生10个0~2之间的y坐标
# 2.创建一张figure
fig = plt.figure(1)
# 3. 设置颜色 color 值【可选参数,即可填可不填】,方式有几种
# colors = np.random.rand(n) # 随机产生10个0~1之间的颜色值,或者
colors = ['r', 'g', 'y', 'b', 'r', 'c', 'g', 'b', 'k', 'm']  # 可设置随机数取
# 4. 设置点的面积大小 area 值 【可选参数】
area = 20*np.arange(1, n+1)
# 5. 设置点的边界线宽度 【可选参数】
widths = np.arange(n)# 0-9的数字
# 6. 正式绘制散点图:scatter
plt.scatter(x, y, s=area, c=colors, linewidths=widths, alpha=0.5, marker='o')
# 7. 设置轴标签:xlabel、ylabel
#设置X轴标签
plt.xlabel('X坐标')
#设置Y轴标签
plt.ylabel('Y坐标')
# 8. 设置图标题:title
plt.title('test绘图函数')
# 9. 设置轴的上下限显示值:xlim、ylim
# 设置横轴的上下限值
plt.xlim(-0.5, 2.5)
# 设置纵轴的上下限值
plt.ylim(-0.5, 2.5)
# 10. 设置轴的刻度值:xticks、yticks
# 设置横轴精准刻度
plt.xticks(np.arange(np.min(x)-0.2, np.max(x)+0.2, step=0.3))
# 设置纵轴精准刻度
plt.yticks(np.arange(np.min(y)-0.2, np.max(y)+0.2, step=0.3))
# 也可按照xlim和ylim来设置
# 设置横轴精准刻度
plt.xticks(np.arange(-0.5, 2.5, step=0.5))
# 设置纵轴精准刻度
plt.yticks(np.arange(-0.5, 2.5, step=0.5))
 
# 11. 在图中某些点上(位置)显示标签:annotate
# plt.annotate("(" + str(round(x[2], 2)) + ", " + str(round(y[2], 2)) + ")", xy=(x[2], y[2]), fontsize=10, xycoords='data')# 或者
plt.annotate("({0},{1})".format(round(x[2],2), round(y[2],2)), xy=(x[2], y[2]), fontsize=10, xycoords='data')
# xycoords='data' 以data值为基准
# 设置字体大小为 10
# 12. 在图中某些位置显示文本:text
plt.text(round(x[6],2), round(y[6],2), "good point", fontdict={'size': 10, 'color': 'red'})  # fontdict设置文本字体
# Add text to the axes.
# 13. 设置显示中文
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
# 14. 设置legend,【注意,'绘图测试':一定要是可迭代格式,例如元组或者列表,要不然只会显示第一个字符,也就是legend会显示不全】
plt.legend(['绘图测试'], loc=2, fontsize=10)
# plt.legend(['绘图测试'], loc='upper left', markerscale = 0.5, fontsize = 10) #这个也可
# markerscale:The relative size of legend markers compared with the originally drawn ones.
# 15. 保存图片 savefig
plt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)
# dpi: The resolution in dots per inch,设置分辨率,用于改变清晰度
# If *True*, the axes patches will all be transparent
# 16. 显示图片 show
plt.show()

scatter主要参数:

def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
                vmin=None, vmax=None, alpha=None, linewidths=None,
                verts=None, edgecolors=None,
                **kwargs):
        """
        A scatter plot of *y* vs *x* with varying marker size and/or color.
        Parameters
        ----------
        x, y : array_like, shape (n, )
            The data positions.
        s : scalar or array_like, shape (n, ), optional
            The marker size in points**2.
            Default is ``rcParams['lines.markersize'] ** 2``.
        c : color, sequence, or sequence of color, optional, default: 'b'
            The marker color. Possible values:
            - A single color format string.
            - A sequence of color specifications of length n.
            - A sequence of n numbers to be mapped to colors using *cmap* and
              *norm*.
            - A 2-D array in which the rows are RGB or RGBA.
            Note that *c* should not be a single numeric RGB or RGBA sequence
            because that is indistinguishable from an array of values to be
            colormapped. If you want to specify the same RGB or RGBA value for
            all points, use a 2-D array with a single row.
        marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
            The marker style. *marker* can be either an instance of the class
            or the text shorthand for a particular marker.
            See `~matplotlib.markers` for more information marker styles.
        cmap : `~matplotlib.colors.Colormap`, optional, default: None
            A `.Colormap` instance or registered colormap name. *cmap* is only
            used if *c* is an array of floats. If ``None``, defaults to rc
            ``image.cmap``.
        alpha : scalar, optional, default: None
            The alpha blending value, between 0 (transparent) and 1 (opaque).
        linewidths : scalar or array_like, optional, default: None
            The linewidth of the marker edges. Note: The default *edgecolors*
            is 'face'. You may want to change this as well.
            If *None*, defaults to rcParams ``lines.linewidth``.

设置legend,【注意,'绘图测试’:一定要是可迭代格式,例如元组或者列表,要不然只会显示第一个字符,也就是legend会显示不全】

plt.legend(['绘图测试'], loc=2, fontsize = 10)
# plt.legend(['绘图测试'], loc='upper left', markerscale = 0.5, fontsize = 10) #这个也可
#  markerscale:The relative size of legend markers compared with the originally drawn ones.

其参数loc对应为:

运行结果:

补充

除了二维的散点图,Python还能绘制三维的散点图,下面的示例代码

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
 
# 随机种子
np.random.seed(1)
 
 
def randrange(n, vmin, vmax):
    '''
    使数据分布均匀(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin
 
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')  # 可进行多图绘制
 
n = 500
 
# 对于每一组样式和范围设置,在由x在[23,32]、y在[0,100]、
# z在[zlow,zhigh]中定义的框中绘制n个随机点
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)  # 绘图
 
# X、Y、Z的标签
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
 
plt.show()

输出结果:

到此这篇关于Python绘制散点图的教程详解的文章就介绍到这了,更多相关Python散点图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 教你使用TensorFlow2识别验证码

    教你使用TensorFlow2识别验证码

    验证码是根据随机字符生成一幅图片,然后在图片中加入干扰象素,本文主要介绍了 TensorFlow2识别验证码,需要的朋友们下面随着小编来一起学习学习吧
    2021-06-06
  • Python中PyQt5可视化界面通过拖拽来上传文件的实现

    Python中PyQt5可视化界面通过拖拽来上传文件的实现

    本文主要介绍了Python中PyQt5可视化界面通过拖拽来上传文件的实现,通过构建一个可接受拖拽的区域,并重写相关事件处理函数,可以方便地实现文件上传功能,具有一定的参考价值,感兴趣的可以了解一下
    2023-12-12
  • Python网络爬虫中的同步与异步示例详解

    Python网络爬虫中的同步与异步示例详解

    这篇文章主要给大家介绍了关于Python网络爬虫中同步与异步的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2018-02-02
  • 实现python namedtuple元类编程

    实现python namedtuple元类编程

    这篇文章主要为大家介绍了实现python namedtuple元类编程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • Python中__init__.py文件的作用

    Python中__init__.py文件的作用

    这篇文章主要介绍了Python中__init__.py文件的作用,在PyCharm中,带有__init__.py这个文件的目录被认为是Python的包目录,与普通目录的图标有不一样的显示
    2022-09-09
  • pycharm快捷键汇总

    pycharm快捷键汇总

    本文给大家分享的是PyCharm开发工具的快捷键大全整理,非常详细,适合使用PyCharm作为开发工具的开发人员参考使用,能够帮助提高开发效率和速度
    2020-02-02
  • python通过函数属性实现全局变量的方法

    python通过函数属性实现全局变量的方法

    这篇文章主要介绍了python通过函数属性实现全局变量的方法,实例分析了Python中函数属性的相关使用技巧,需要的朋友可以参考下
    2015-05-05
  • python使用cookielib库示例分享

    python使用cookielib库示例分享

    Python中cookielib库(python3中为http.cookiejar)为存储和管理cookie提供客户端支持,下面是使用示例
    2014-03-03
  • Pycharm自动添加文件头注释和函数注释参数的方法

    Pycharm自动添加文件头注释和函数注释参数的方法

    这篇文章主要介绍了Pycharm自动添加文件头注释和函数注释参数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • ubuntu系统如何从python3.7升级到python3.8

    ubuntu系统如何从python3.7升级到python3.8

    这篇文章主要给大家介绍了关于ubuntu系统如何从python3.7升级到python3.8的相关资料,Python是一种广泛使用的编程语言,而Ubuntu是一个流行的开源操作系统,通过升级Python您可以获得新功能、性能改进和安全修复,需要的朋友可以参考下
    2023-11-11

最新评论