• 【matplotlib】绘制散点图,为不同区域的点添加不同颜色+添加纵向\横向分割线(含Python代码实例)


    我们利用matplotlib绘制散点图,并且为不同的区域添加不同的颜色。

    1. 为不同区域添加不同的颜色

    import numpy as np
    import matplotlib.pyplot as plt
    
    x2 = list(map(int, np.random.random_sample(100) * 100))
    y2 = list(map(int, np.random.random_sample(100) * 100))
    
    split_x = split_y = 80
    colors = []
    
    for x, y in zip(x2, y2):
        if x > split_x:
            if y > split_y:  # 第一象限
                colors.append('red')
            else:  # 第四象限
                colors.append('blue')
        else:
            if y > split_y:  # 第二象限
                colors.append('yellow')
            else:  # 第三象限
                colors.append('green')
    plt.scatter(x2, y2, c=colors)
    plt.xlim([0, 100])
    plt.ylim([0, 100])
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    结果展示为:

    在这里插入图片描述
    可以看到,不同区域的点的颜色不同!

    2. 添加纵向、横向分割线

    需要加入两行代码:

    plt.plot([split_y]*100,'c--')
    plt.plot([split_x]*100,list(range(0,100)),'c--')
    
    • 1
    • 2

    其中,plt.plot([split_y]*100,'c--')表示的是添加横向分隔线;plt.plot([split_x]*100,list(range(0,100)),'c--')表示的是添加纵向分隔线。

    全部代码展示如下:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x2 = list(map(int, np.random.random_sample(100) * 100))
    y2 = list(map(int, np.random.random_sample(100) * 100))
    
    split_x = split_y = 80
    colors = []
    
    for x, y in zip(x2, y2):
        if x > split_x:
            if y > split_y:  # 第一象限
                colors.append('red')
            else:  # 第四象限
                colors.append('blue')
        else:
            if y > split_y:  # 第二象限
                colors.append('yellow')
            else:  # 第三象限
                colors.append('green')
    plt.plot([split_y]*100,'c--')
    plt.plot([split_x]*100,list(range(0,100)),'c--')
    plt.scatter(x2, y2, c=colors)
    plt.xlim([0, 100])
    plt.ylim([0, 100])
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    效果展示如下:

    在这里插入图片描述

  • 相关阅读:
    一文带你了解MySQL数据库基础
    MySQL学习笔记
    MySQL中字符串比较大小(日期字符串比较问题)
    谁把我网站攻击了
    多向思考者--高敏感人群的内心世界
    《论文阅读》任务型对话中融合KB实体的方法
    Altium Designer 相同电路多组复制布线
    jsp初学
    代码演示傅里叶合成演示
    .NET开发工作效率提升利器 - CodeGeeX AI编程助手
  • 原文地址:https://blog.csdn.net/wzk4869/article/details/126923055