• 生成数据


    绘  图

    参考:https://blog.csdn.net/anneqiqi/article/details/64125186

    折线图

    import matplotlib.pyplot as plt
    
    squares = [1, 4, 9, 16, 25]
    plt.plot(squares)
    plt.show()

    修改标签文字、线条粗细

    import matplotlib.pyplot as plt
    
    squares = [1, 4, 9, 16, 25]
    plt.plot(squares, linewidth = 5)
    
    # 设置标签
    plt.title("Square Number", fontsize = 24)
    plt.xlabel("Value", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置刻度大小
    plt.tick_params(axis = 'both', labelsize = 14)
    
    plt.show()

    校正图形

    import matplotlib.pyplot as plt
    
    input_values = [1, 2, 3, 4, 5]
    squares = [1, 4, 9, 16, 25]
    plt.plot(input_values, squares, linewidth = 5)  # 第一个参数为x轴的值即输入值
    """
    plot()函数默认第一个数据点为(0, 0)
    """
    
    # 设置标签
    plt.title("Square Number", fontsize = 24)
    plt.xlabel("Value", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置刻度大小
    plt.tick_params(axis = 'both', labelsize = 14)
    
    plt.show()

    使用 scatter() 函数绘制散点图、设置其样式

    import matplotlib.pyplot as plt
    
    plt.scatter(2, 4)   # 设置一个坐标
    plt.show()
    import matplotlib.pyplot as plt
    
    plt.scatter(2, 4, s = 200)   # 设置一个坐标
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Valve", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置刻度标记的大小
    plt.tick_params(axis = 'both', which = 'major', labelsize = 14)
    
    plt.show()

    使用 scatter() 绘制一系列的点

    import matplotlib.pyplot as plt
    
    x_values = [1, 2, 3, 4, 5]
    y_values = [1, 4, 9, 16, 25]
    
    plt.scatter(x_values, y_values, s = 100)    # s参数表示点的直径
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 刻度设置
    plt.tick_params(axis = 'both', which = 'major', labelsize = 14)
    
    plt.show()

    自动计算数据

    """自动计算数据"""
    
    import matplotlib.pyplot as plt
    
    x_values = list(range(1, 1001))
    y_values = [x**2 for x in x_values]
    
    plt.scatter(x_values, y_values, s = 4)
    
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置每个坐标轴的取值范围
    plt.axis([0, 1100, 0, 1100000])
    
    plt.show()

    删除数据点的轮廓

    """自动计算数据"""
    
    import matplotlib.pyplot as plt
    
    x_values = list(range(1, 1001))
    y_values = [x**2 for x in x_values]
    
    plt.scatter(x_values, y_values, edgecolor = 'none', s = 4)
    # edgecolor 参数蓝色点黑色轮廓,去掉黑色轮廓后显示为蓝色实心点
    
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置每个坐标轴的取值范围
    plt.axis([0, 1100, 0, 1100000])
    
    plt.show()

    自定义颜色

    """自动计算数据"""
    
    import matplotlib.pyplot as plt
    
    x_values = list(range(1, 1001))
    y_values = [x**2 for x in x_values]
    
    plt.scatter(x_values, y_values, c = 'red', edgecolor = 'none', s = 4)
    # edgecolor 参数蓝色点黑色轮廓,去掉黑色轮廓后显示为蓝色实心点
    # c 参数表示颜色,可以用元组 RGB 值表示颜色
    
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置每个坐标轴的取值范围
    plt.axis([0, 1100, 0, 1100000])
    
    plt.show()

    使用颜色映射

    """自动计算数据"""
    
    import matplotlib.pyplot as plt
    
    x_values = list(range(1, 1001))
    y_values = [x**2 for x in x_values]
    
    plt.scatter(x_values, y_values, c = y_values,cmap = plt.cm.Blues, edgecolor = 'none', s = 4)
    # c 参数的值越大,blues 颜色的值越深,渐变
    
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置每个坐标轴的取值范围
    plt.axis([0, 1100, 0, 1100000])
    
    plt.show()

    自动保存图表

    """自动计算数据"""
    
    import matplotlib.pyplot as plt
    
    x_values = list(range(1, 1001))
    y_values = [x**3 for x in x_values]
    
    plt.scatter(x_values, y_values, c = y_values,cmap = plt.cm.Blues, edgecolor = 'none', s = 4)
    # c 参数的值越大,blues 颜色的值越深,渐变
    
    
    plt.title("Square Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 14)
    plt.ylabel("Square of Value", fontsize = 14)
    
    # 设置每个坐标轴的取值范围
    plt.axis([0, 1100, 0, 1100000])
    
    plt.show()
    
    plt.savefig('xieyi.png', bbox_inches = 'tight')
    # 自动保存图表,第二个参数裁剪图表周围多余空白区域

    随机漫步

    from random import choice
    
    import matplotlib.pyplot as plt
    
    class RandomWalk():
        # 一个生成随机漫步数据的类
    
        def __init__(self, num_points = 500):
            self.num_points = num_points
    
            self.x_values = [0]
            self.y_values = [0]
    
        def fill_walk(self):
    
            while len(self.x_values) < self.num_points:
    
                x_direction = choice([1, -1])
                x_distance = choice([0, 1, 2, 3, 4])
                x_step = x_direction * x_distance
    
                y_direction = choice([1, 1])
                y_distance = choice([0, 1, 2, 3, 4])
                y_step = y_direction * y_distance
    
    
                if x_step == 0 and y_step ==0:
                    continue
    
                next_x = self.x_values[-1] + x_step
                next_y = self.y_values[-1] + y_step
    
                self.x_values.append(next_x)
                self.y_values.append(next_y)
    
    rw = RandomWalk()
    rw.fill_walk()
    plt.scatter(rw.x_values, rw.y_values, s = 10)
    
    plt.title("Numbers", fontsize = 24)
    plt.xlabel("Values", fontsize = 20)
    plt.ylabel("Numbers of Values", fontsize = 20)
    
    plt.show()

    模拟多次随机漫步

    from random import choice
    
    import matplotlib.pyplot as plt
    
    class RandomWalk():
        # 一个生成随机漫步数据的类
    
        def __init__(self, num_points = 500):
            self.num_points = num_points
    
            self.x_values = [0]
            self.y_values = [0]
    
        def fill_walk(self):
    
            while len(self.x_values) < self.num_points:
    
                x_direction = choice([1, -1])
                x_distance = choice([0, 1, 2, 3, 4])
                x_step = x_direction * x_distance
    
                y_direction = choice([1, 1])
                y_distance = choice([0, 1, 2, 3, 4])
                y_step = y_direction * y_distance
    
    
                if x_step == 0 and y_step ==0:
                    continue
    
                next_x = self.x_values[-1] + x_step
                next_y = self.y_values[-1] + y_step
    
                self.x_values.append(next_x)
                self.y_values.append(next_y)
    
    while True:
        rw = RandomWalk()
        rw.fill_walk()
        plt.scatter(rw.x_values, rw.y_values, s = 10)
    
        plt.title("Numbers", fontsize = 24)
        plt.xlabel("Values", fontsize = 20)
        plt.ylabel("Numbers of Values", fontsize = 20)
    
        plt.show()
    
        keep_runing = input("Make another walk?(y/n):")
        if keep_runing == 'n':
            break

    设置随机漫步图的样式

    from random import choice
    
    import matplotlib.pyplot as plt
    
    class RandomWalk():
        # 一个生成随机漫步数据的类
    
        def __init__(self, num_points = 500):
            self.num_points = num_points
    
            self.x_values = [0]
            self.y_values = [0]
    
        def fill_walk(self):
    
            while len(self.x_values) < self.num_points:
    
                x_direction = choice([1, -1])
                x_distance = choice([0, 1, 2, 3, 4])
                x_step = x_direction * x_distance
    
                y_direction = choice([1, 1])
                y_distance = choice([0, 1, 2, 3, 4])
                y_step = y_direction * y_distance
    
    
                if x_step == 0 and y_step ==0:
                    continue
    
                next_x = self.x_values[-1] + x_step
                next_y = self.y_values[-1] + y_step
    
                self.x_values.append(next_x)
                self.y_values.append(next_y)
    
    while True:
        rw = RandomWalk()
        rw.fill_walk()
    
        # 给点着色
        point_number = list(range(rw.num_points))
        plt.scatter(rw.x_values, rw.y_values, c = point_number, cmap = plt.cm.Blues,
                    edgecolor = 'none', s = 20)
    
        
        plt.show()
    
        keep_runing = input("Make another walk?(y/n):")
        if keep_runing == 'n':
            break

    重新绘制起点和重终点

    隐藏坐标轴

    增加点数

    调整屏幕以合适的尺寸

    from random import choice
    
    import matplotlib.pyplot as plt
    
    class RandomWalk():
        # 一个生成随机漫步数据的类
    
        def __init__(self, num_points = 500):
            self.num_points = num_points
    
            self.x_values = [0]
            self.y_values = [0]
    
        def fill_walk(self):
    
            while len(self.x_values) < self.num_points:
    
                x_direction = choice([1, -1])
                x_distance = choice([0, 1, 2, 3, 4])
                x_step = x_direction * x_distance
    
                y_direction = choice([1, 1])
                y_distance = choice([0, 1, 2, 3, 4])
                y_step = y_direction * y_distance
    
    
                if x_step == 0 and y_step ==0:
                    continue
    
                next_x = self.x_values[-1] + x_step
                next_y = self.y_values[-1] + y_step
    
                self.x_values.append(next_x)
                self.y_values.append(next_y)
    
    while True:
        rw = RandomWalk(50000)  # 增加点数
        rw.fill_walk()
    
        # 设置绘图窗口的尺寸
        plt.figure(figsize = (10, 6))
    
        # 给点着色,绘制点并将图形显示出来
        point_number = list(range(rw.num_points))
        plt.scatter(rw.x_values, rw.y_values, c = point_number, cmap = plt.cm.Blues,
                    edgecolor = 'none', s = 1)
    
        # 突出起点和终点
        plt.scatter(0, 0, c = 'green', edgecolors = 'none', s = 100)
        plt.scatter(rw.x_values[-1], rw.y_values[-1], c = 'red', edgecolors = 'none',
                    s = 100)
    
        # 隐藏坐标轴
        plt.axes().get_xaxis().set_visible(False)
        plt.axes().get_yaxis().set_visible(False)
    
        plt.show()
    
        keep_runing = input("Make another walk?(y/n):")
        if keep_runing == 'n':
            break

    使用 Pygal 包:生成矢量图像,不同屏幕自动调整大小

    from random import randint
    
    import pygal
    
    class Die():
    
        def __init__(self, num_sides = 6):
            self.num_sides = num_sides
    
        def roll(self):
            return randint(1, self.num_sides)
    
    die = Die()
    
    results = []
    for roll_num in range(100):
        result = die.roll()
        results.append(result)
    
    print(results)
    
    # 分析结果
    frequencies = []
    for value in range(1, die.num_sides+1):
        frequency = results.count(value)
        frequencies.append(frequency)
    print(frequencies)
    
    # 可视化数据
    hist = pygal.Bar()
    
    hist.title = "Results of rolling one D6 1000 times"
    hist.x_values = ['1','2','3', '4', '5', '6']
    hist.x_title = "Result"
    hist.y_title = "Frequencies"
    
    hist.add('D6', frequencies)
    hist.render_to_file('xieyi.svg')    # 渲染为一个svg文件,svg用浏览器打开
    from random import randint
    
    import pygal
    
    class Die():
    
        def __init__(self, num_sides = 6):
            self.num_sides = num_sides
    
        def roll(self):
            return randint(1, self.num_sides)
    
    die_1 = Die()
    die_2 = Die()
    
    results = []
    for roll_num in range(1000):
        result = die_1.roll() + die_2.roll()
        results.append(result)
    
    print(results)
    
    # 分析结果
    frequencies = []
    max_result = die_1.num_sides + die_2.num_sides
    for value in range(2, max_result+1):
        frequency = results.count(value)
        frequencies.append(frequency)
    print(frequencies)
    
    # 可视化数据
    hist = pygal.Bar()
    
    hist.title = "Results of rolling one D6 1000 times"
    hist.x_labels = ['2','3', '4', '5', '6', '7', '8', '9','10', '11', '12']
    hist.x_title = "Result"
    hist.y_title = "Frequencies"
    
    hist.add('D6 + D6', frequencies)
    hist.render_to_file('xieyi01.svg')    # 渲染为一个svg文件,svg用浏览器打开
  • 相关阅读:
    Redis为什么使用单进程单线程方式也这么快
    数据库表设计五大范式所解决的问题
    数据库范式那些事
    线上Java程序导致服务器CPU占用率过高的问题排除过程
    对分布式事务及两阶段提交、三阶段提交的理解
    About the diffrence of wait timed_wait and block in java
    Linux io Model
    阻塞与非阻塞,同步与异步
    深入理解JAVA I/O系列六:Linux中的IO模型(转载的文章非常值得学习)
    真正的Maven经常使用命令
  • 原文地址:https://www.cnblogs.com/xieyi-newlife/p/9064432.html
Copyright © 2020-2023  润新知