【Python学习笔记】【matplotlib】(十三)数据可视化:生成数据(折线图、散点图、直方图)

官方文件:https://matplotlib.org/

生成数据

绘制简单的折现图

折线图

import matplotlib.pyplot as plt # 包含生成图表的函数

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y, linewidth=5) # 设置图像线条宽度

# 设置图表标题、坐标轴标签,并指定图标中文字大小
plt.title("Square Numbers", fontsize=14)
plt.xlabel("x", fontsize=14)
plt.ylabel("x^2", fontsize=14)

# 设置刻度标记
plt.tick_params(axis='both', labelsize=14)

plt.show() # 打开matplotlib查看器

散点图

import matplotlib.pyplot as plt # 包含生成图表的函数

x = list(range(1, 1001))
y = [x**2 for x in x.copy()]

# 传递实参,修改颜色,颜色也可以是RGB值;消除点的黑色轮廓,显示蓝色实心点
plt.scatter(x, y, c='red', edgecolors='none')

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

plt.show()

使用颜色映射/渐变色:plt.scatter(x, y, c=y, cmap=plt.cm.Blues, edgecolors='none')

保存图表:plt.savefig('1.png', bbox_inches='tight')
第一个实参指定文件名;第二个实参用来去除图表周围的空白区域,可省略

彩色立方:

from matplotlib import pyplot as plt

x_values = list(range(5001))
cubes = [x**3 for x in x_values]

plt.scatter(x_values, cubes, c=cubes, cmap=plt.cm.PuRd, edgecolor='none', s=20)

plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.axis([0, 5100, 0, 5100**3])

plt.show()

颜色参数
【Python学习笔记】【matplotlib】(十三)数据可视化:生成数据(折线图、散点图、直方图)_第1张图片

随机漫步

随机漫步的路径:每次行走都是完全随机的,没有明确的方向

import matplotlib.pyplot as plt
from random import choice # 随机选择

class RandomWalk():
    def __init__(self, num_poins=5000):
        self.num_points = num_poins # 随机漫步的点数

        # 起始位置
        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]) # 随机选择-1/1
            x_distance = choice(list(range(5))) # 随机0-4的整数
            x_step = x_direction * x_distance
            y_direction = choice([-1, 1])
            y_distance = choice(list(range(5)))
            y_step = y_direction * y_distance
            if x_step == 0 or 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(6000) # 可指定点数
    rw.fill_walk()

    # 调整屏幕尺寸
    plt.figure(dpi=128, figsize=(10,6)) # 分辨率;一个元组表示宽高(英寸)

    # 按照点出现的先后次序给点着色,由浅到深
    point_numbers = list(range(rw.num_points)) # 序号1-5000
    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Purples, edgecolors='none', s=10)

    # 标明起点终点
    plt.scatter(0, 0, c='green')
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red')

    # 多次模拟
    if (input("Make anonther walk?(y/n):")) == 'n':
        break

    plt.show()

分子运动

import matplotlib.pyplot as plt
from random import choice # 随机选择

class RandomWalk():
    def __init__(self, num_poins=5000):
        self.num_points = num_poins # 随机漫步的点数

        # 起始位置
        self.x_values = [0]
        self.y_values = [0]

    # 前进
    def get_step(self):
        direction = choice([-1, 1])  # 随机选择-1/1
        distance = choice(list(range(5)))  # 随机0-4的整数
        step = direction * distance
        return step

    # 漫步
    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            # 前进
            x_step = self.get_step()
            y_step = self.get_step()
            if x_step == 0 or 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(5000) # 可指定点数
    rw.fill_walk()

    plt.plot(rw.x_values, rw.y_values,  linewidth=1) # 细一点,不然就是一坨

    # 标明起点终点
    plt.scatter(0, 0, c='green', s=20) # 字体调大点,不然看不见
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', s=20)

    # 多次模拟
    if (input("Make anonther walk?(y/n):")) == 'n':
        break

    plt.show()

掷骰子(Pygal包)

Python可视化包Pygal来生成缩放的适量图形文件(放大-缩小)。

import pygal
from random import randint # 随机数

# 骰子类
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 x in range(100):
    result = die.roll()
    results.append(result)
 # print(results)

 # 分析结果
frequencies = []
for y in range(1, die.num_sides+1):
    frequency = results.count(y) # 统计列表中元素出现个数
    frequencies.append(frequency)
# print(frequencies)

# 进行结果可视化
hist = pygal.Bar() # 一个条形图实例
hist.title = "Result of rolling one D6 for 100 times"
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency"

hist.add('D6', frequencies) # 向表中添加值
hist.render_to_file('die_visual.svg') # 将图表渲染为SVG文件

生成的SVG文件可以用Web浏览器打开。
【Python学习笔记】【matplotlib】(十三)数据可视化:生成数据(折线图、散点图、直方图)_第2张图片

多个筛子:两个面数不同的

import pygal
from random import randint # 随机数

# 骰子类
class Die():
    def __init__(self, num_sides=6):
        self.num_sides = num_sides # 骰子面数

    # 返回点数
    def roll(self):
        return randint(1, self.num_sides)

die1 = Die() # 6面
die2 = Die(8) # 8面

# 多次掷骰子
results = []
for x in range(50000):
    result = die1.roll() + die2.roll()
    results.append(result)
 # print(results)

 # 分析结果
frequencies = []
for y in range(1, die1.num_sides + die2.num_sides + 1):
    frequency = results.count(y) # 统计列表中元素出现个数
    frequencies.append(frequency)
# print(frequencies)

# 进行结果可视化
hist = pygal.Bar() # 一个条形图实例
hist.title = "Result of rolling D6 + D8 for 50,000 times"
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
hist.x_title = "Result"
hist.y_title = "Frequency"

hist.add('D6 + D8', frequencies) # 向表中添加值
hist.render_to_file('die_visual2.svg') # 将图表渲染为SVG文件

你可能感兴趣的:(项目)