【python3】第15章生成数据

绘制简单的折线图

import matplotlib.pyplot as plt
 
input_values = [12345]
squares = [1491625]
 
plt.plot(input_values, squares, linewidth=5)  # 决定plot()绘制的线条的粗细
plt.title('Square Numbers', fontsize=24)  # 给图标设置标题
plt.xlabel('Value', fontsize=14)  # 为x轴设置标题
plt.ylabel('Square of Value', fontsize=14)  # 为y轴设置标题
 
plt.tick_params(axis='both', labelsize=10)  # 设置刻度的样式,axis=x/y
 
plt.show()  # 打开matplotlib查看器,并显示绘制的图形


 

绘制散点图

import matplotlib.pyplot as plt
 
x_values = [12345]
# y_values = [1491625]
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, c='red', edgecolors='none', s=40)  # 设置点的颜色,删除数据点的轮廓,绘制图形时使用的点的尺寸
 
plt.title('Square Number', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
 
plt.tick_params(axis="both", which='major', labelsize=10)
plt.axis([0500100])  # 设置每个坐标轴的取值范围
 
plt.show()

import matplotlib.pyplot as plt
 
x_values = [12345]
y_values = [x**2 for x in x_values]、
# 颜色映射,从起始颜色渐变到结束颜色。将参数c设置成一个y值列表,并使用参数cmap告诉pyplot使用哪个颜色映射
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors='none', s=40
 
plt.title('Square Number', fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
 
plt.tick_params(axis="both", which='major', labelsize=10)
plt.axis([0500100])
 
plt.show()
 
 
# plt.savefig('squares_plot.png', bbox_inches='tight')
# 第一个实参指定要以什么样的文件名保存图标,将存储在scatter_squares.py所在目录中
# 第二个实参指定图标多余的空白区域裁剪掉。如果要保留周围空白区域,可省略这个实参

 

随机漫步

1、RandomWalk的类,它随机选择前进方向。这个类需要三个属性,一个是存储随机漫步次数的变量,其他两个是列表,分别存储随机漫步经过的每个点的x和y的坐标

random_walk
from random import choice
 
class RandomWalk():
    """一个生成随机漫步数据的类"""
 
    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:
            # 决定前进方向以及沿这个方向前进的距离
            x_direction = choice([1-1])
            x_distance = choice([01234])  # 随机选择一个0~4之间的整数
            x_step = x_direction * x_distance
 
            y_direction = choice([1-1])
            y_distance = choice([01234])
            y_step = y_direction * y_distance
 
            # 拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue
 
            # 计算下一个点的x和y值
            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_visual
import matplotlib.pyplot as plt
from test_matplotlib.random_walk import RandomWalk
 
# 只要程序处于活动状态,就不断地模拟随机漫步
while True:
    # 创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()
 
    # 设置绘图窗口的尺寸。dpi向figure()传递该分辨率
    plt.figure(dpi=128, figsize=(106))
 
    point_number = list(range(rw.num_points))
    plt.scatter(rw.x_values, rw.y_values, c=point_number, cmap=plt.cm.Blues,
                edgecolors='none', s=1)
    plt.title('包含n个点的随机漫步', fontsize=24)
 
    # 突出起点和终点
    plt.scatter(00, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
 
    # 隐藏坐标轴,使用plt.axes()来将每条坐标轴的可见性设置为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模拟掷骰子

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(1self.num_sides)
die_visual
import pygal
from test_matplotlib.die import Die
 
# 创建一个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 = []
max_result = die_1.num_sides + die_2.num_sides  # 可能出现的最大点数12为俩个骰子的最大可能点数之和,存储到max_result
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 a D10 50,000 times'
hist.x_labels = ['2''3''4''5''6''7''8''9''10''11''12''13''14''15''16']
hist.x_title = 'Result'
hist._y_title = 'Frequency of Result'
 
# 使用add()将一系列值添加到图表中(向它传递要给添加的值指定的标签,还有一个列表,其中包含将出现在图标中的值。
# 将这个图表渲染成一个svg文件)
hist.add('D6 + D10', frequencies)
hist.render_to_file('die_visual.svg')

 

原文地址:https://www.cnblogs.com/CSgarcia/p/13267956.html