数据可视化(生成数据)

绘制简单折线图

初始代码如下:

import matplotlib.pyplot as plt

squares = [1, 4, 8, 16, 25]
plt.plot(squares)
plt.show()

初始效果图如下:
在这里插入图片描述
matplotlib是一个数学绘图库,可以用它来制作简单的图表,如折线图和散点图

Step 1:修改标签文字和线条粗细

# 导入模块pyplot(包含很多用于生成图表的函数),并为其指定别名plt
import matplotlib.pyplot as plt

# 创建一个列表,在其中存储平方数
squares = [1, 4, 8, 16, 25]

# 将列表传递给函数plot(),linewidth决定了绘制的线条的粗细
plt.plot(squares, linewidth=5)

# 设置图表标题,并给坐标轴加上标签
# title()为图表指定标题;
plt.title("Square Numbers", fontsize=24)
# xlabel()和ylabel()为每条轴设置标题;fontsize为字号大小
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# 设置刻度标记大小;labelsize为字号大小
plt.tick_params(axis='both', labelsize=14)

# 打开matplotlib查看器,并显示绘制的图形
plt.show()

在这里插入图片描述

Step 2:校正图形

# 导入模块pyplot(包含很多用于生成图表的函数),并为其指定别名plt
import matplotlib.pyplot as plt

# 原本假设的第一个数据点对应的x坐标值为0,现提供输入值将第一个对应的x值改为1
input_values = [1, 2, 3, 4, 5]
# 创建一个列表,在其中存储平方数
squares = [1, 4, 8, 16, 25]

# 将列表传递给函数plot(),linewidth决定了绘制的线条的粗细
plt.plot(input_values, squares, linewidth=5)

# 设置图表标题,并给坐标轴加上标签
# 下面的省略

在这里插入图片描述

绘制散点图

import matplotlib.pyplot as plt

# 使用函数scatter(),向其传递一对x和y坐标,它将在指定位置绘制一个点
# s表示点的尺寸
plt.scatter(2, 4, s=200)

# 设置图表标题,并给坐标轴加上标签
# title()为图表指定标题;
plt.title("Square Numbers", fontsize=24)
# xlabel()和ylabel()为每条轴设置标题;fontsize为字号大小
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# 设置刻度标记大小;labelsize为字号大小
plt.tick_params(axis='both', which='major', labelsize=14)

plt.show()

在这里插入图片描述

Step 1:绘制一系列的点

import matplotlib.pyplot as plt

# x_values包含要计算其平方值的数字,y_values包含前述每个数字的平方和
# 讲这些列表传递给scatter()时,matplotlib依次从每个列表中读取一个值来绘制一个点
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]

# 使用函数scatter(),向其传递一对x和y坐标,它将在指定位置绘制一个点
# s表示点的尺寸
plt.scatter(x_values, y_values, s=100)

# 设置图表标题,并给坐标轴加上标签
# 下面的省略

在这里插入图片描述

Step 2:自动计算数据

import matplotlib.pyplot as plt

# x_values包含要计算其平方值的数字,y_values包含前述每个数字的平方和
# 讲这些列表传递给scatter()时,matplotlib依次从每个列表中读取一个值来绘制一个点
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]

# 使用函数scatter(),向其传递一对x和y坐标,它将在指定位置绘制一个点
# s表示点的尺寸
plt.scatter(x_values, y_values, s=40)
# 加上语句 c='red' 可将蓝色点改为红色(可自行选择颜色)
# 加上语句 edgecolors='none' 可消除蓝色点的黑色边框(可自行选择颜色)
# plt.scatter(x_values, y_values, c='red', edgecolors='none',  s=40)

# 设置图表标题,并给坐标轴加上标签
# title()为图表指定标题;
plt.title("Square Numbers", fontsize=24)
# xlabel()和ylabel()为每条轴设置标题;fontsize为字号大小
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# 设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])

plt.show()

在这里插入图片描述

Step 3:使用颜色映射并保存图表

import matplotlib.pyplot as plt

# x_values包含要计算其平方值的数字,y_values包含前述每个数字的平方和
# 讲这些列表传递给scatter()时,matplotlib依次从每个列表中读取一个值来绘制一个点
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]

# 使用函数scatter(),向其传递一对x和y坐标,它将在指定位置绘制一个点
# s表示点的尺寸
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors='none',  s=40)

# 设置图表标题,并给坐标轴加上标签
# title()为图表指定标题;
plt.title("Square Numbers", fontsize=24)
# xlabel()和ylabel()为每条轴设置标题;fontsize为字号大小
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# 设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])

# 自动保存图表,第一个实参指定要以什么样的格式保存图表,第二个实参指定将图表多余的空白区域裁剪掉
plt.savefig('squares_plot.png', bbox_inches='tight')
plt.show()

在这里插入图片描述

随机漫步

Step 1:创建RandomWalk()类

# 每次决策都使用choice()来决定使用哪种选择
from random import choice

class RandomWalk():
    """一个生成随机漫步数据的类"""

    # 将随机漫步包含的默认点数设置为5000
    def __init__(self, num_points=5000):
        """初始化随机漫步的属性"""
        self.num_points = num_points

        # 所有随机漫步都始于(0,0)
        self.x_values = [0]
        self.y_values = [0]

    # 生成漫步包含的点,并决定每次漫步的方向
    # 向右走还是向左走?沿指定的方向走多远?向上走还是向下走?沿指定的方向走多远?
    def fill_walk(self):
        """计算随机漫步包含的所有点"""

        # 不断漫步,直到列表达到指定的长度
        while len(self.x_values) < self.num_points:
            # 决定前进方向以及沿这个方向前进的距离
            # 使用choice([1, -1])给x_direction选择一个值
            # 结果要么是表示向右走的1,要么是表示向左走的-1
            x_direction = choice([1, -1])
            # choice([0, 1, 2, 3, 4])随机选择一个0~4之间的整数,表示沿指定方向走多远
            x_distance = choice([0, 1, 2, 3, 4])
            # 将移动方向乘以移动距离,以确定沿x轴移动的距离
            # 若x_step为正,右移;为负左移;为0垂直移动
            x_step = x_direction * x_distance

            # 结果要么是表示向上走的1,要么是表示向下走的-1
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            # 若y_step为正,上移;为下左移;为0水平移动
            y_step = y_direction * y_distance

            # 若x_step和y_step都为0则原地踏步
            # 拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue

            # 将x_step与x_values的最后一个值相加,y同理
            # 计算下一个点的x和y值
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            # 将获得的下一个x和y的值附加到列表x_values和y_values的末尾
            self.x_values.append(next_x)
            self.y_values.append(next_y)

Step 2:绘制随机漫步图

import matplotlib.pyplot as plt

from random_walk import RandomWalk

# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()

在这里插入图片描述

Step 3:调整图形(如尺寸,颜色等)

import matplotlib.pyplot as plt

from random_walk import RandomWalk

# 只要这个程序处于活动状态,就不断地模拟随机漫步
while True:
    # 创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()

    # 设置绘图窗口的尺寸
    plt.figure(figsize=(10, 6))
    # 使用range()生成一个数字列表,其中包含的数字个数与漫步包含的点数相同
    # 将其存储在point_numbers中,以便后面使用它来设置每个漫步点的颜色
    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
                edgecolors='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)

    # 隐藏坐标轴:将每条坐标轴可见性设置为False
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Make another walk? (y/n):")
    if keep_running == 'n':
        break

在这里插入图片描述

使用 Pygal 模拟掷骰子

Step 1:创建Die类

from random import randint

class Die():
    """表示一个骰子的类"""

    def __init__(self, num_sides=6):
        """骰子默认6面"""
        self.num_sides = num_sides

    def roll(self):
        """返回一个位于1和骰子面数之间的随机值"""
        return randint(1, self.num_sides)

Step 2:掷骰子

from die import Die
import pygal

# 创建一个D6
die = Die()

# 掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

# 分析结果
# 创建空列表frequencies用于存储每种点数出现的次数
frequencies = []
for value in range(1, die.num_sides):
    frequency = results.count(value)
    frequencies.append(frequency)

# 对结果进行可视化
hist = pygal.Bar()

hist.title = "Results of rolling one D6 1000 times."
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

# 将一系列值添加到图表中
hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')

在这里插入图片描述

Step 3:同时掷两个面数不同的骰子

from die import Die
import pygal

# 创建一个D6骰子和一个D10骰子
die_1 = Die()
die_2 = Die(10)

# 掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(50000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

# 分析结果
# 创建空列表frequencies用于存储每种点数出现的次数
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)

# 对结果进行可视化
hist = pygal.Bar()

hist.title = "Results of rolling a D6 and D10 50,000 times."
hist.x_labels = ['2', '3', '4', '5', '5', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

# 将一系列值添加到图表中
hist.add('D6 + D10', frequencies)
hist.render_to_file('die_visual.svg')

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值