当前位置:网站首页>数据可视化

数据可视化

2022-07-17 05:04:00 Morbidmuse

数据可视化

#绘制简单的折线图
import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
# 在一张图片中绘制一张或者多张图表
fig,ax = plt.subplots()
# print(fig,ax)
# >>>Figure(640x480) AxesSubplot(0.125,0.11;0.775x0.77)

# 显示中文
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

# 绘制图表
ax.plot(squares,linewidth=3)  # linewidth设置线条粗细

# 设置图表标题,横纵坐标轴描述
ax.set_title('平方数',fontsize=24)
ax.set_xlabel('值',fontsize=14)
ax.set_ylabel('平方',fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both',labelsize=14)
plt.show()

在这里插入图片描述

# 校正图形
# 向plot()提供一系列数时,它假设第一个数据点对应的x坐标为0,这会造成图形不准确
# 解决方案是同时向其提供输入值和输出值
# mpl_squares.py

mpl_squares.py

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]

# 使用内置样式
plt.style.use('bmh')
fig,ax = plt.subplots()
ax.plot(input_values,squares,linewidth=3)

# 设置图表标题,横纵坐标轴描述
ax.set_title('平方数',fontsize=24)
ax.set_xlabel('值',fontsize=14)
ax.set_ylabel('平方',fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both',labelsize=14)

plt.show()

在这里插入图片描述

#使用内置样式
print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
# 使用scatter()绘制散点图
# catter_squares.py

catter_squares.py

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

plt.style.use('bmh')
fig,ax = plt.subplots()
ax.scatter(2,4,s=200)  # s=200 指的是点的大小
ax.set_title('平方数',fontsize=24)
ax.set_xlabel('值',fontsize=14)
ax.set_ylabel('平方',fontsize=14)

ax.tick_params(axis='both',which='major',labelsize=14)

plt.show()

在这里插入图片描述

# 自动保存图表
# plt.savefig("文件名.png",bbox_inches='tight') # bbox_inches='tight'是否保留图表多余的空白区域,不写这个参数就保留
# 随机漫步
""" 创建RandomWalk类 random_walk.py 它随机地选择前进方向 三个属性 随机漫步次数的变量 两个列表,分别存储随机漫步经过的每个点的x坐标和y坐标 fill_walk()方法计算随机漫步经过的所有点 """
'\n创建RandomWalk类 random_walk.py\n它随机地选择前进方向\n三个属性\n    随机漫步次数的变量\n    两个列表,分别存储随机漫步经过的每个点的x坐标和y坐标\nfill_walk()方法计算随机漫步经过的所有点\n'

random_walk.py


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([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

            # 计算下一个点的x,和y值
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)


# 绘制随机漫步图
# rw_visual.py

rw_visual.py

# 绘制随机漫步的散点图

import matplotlib.pyplot as plt
from random_walk import RandomWalk
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

plt.style.use('classic')
while True:
    rw = RandomWalk(50_000)
    rw.fill_walk()

    fig,ax = plt.subplots(figsize=(15,9))  # figsize=(15,9)用于指定尺寸 单位为英寸
    point_numbers = range(rw.num_points)
    ax.scatter(rw.x_values,rw.y_values,c=point_numbers,  # 应用颜色映射并去掉轮廓色
               cmap=plt.cm.Blues,edgecolors='none',s=1)

    # 重新绘制起点和终点
    ax.scatter(0,0,c='green',edgecolors='none',s=100)
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
    # 隐藏坐标轴
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    # ax.plot(rw.x_values,rw.y_values)
    plt.show()

    keep_running = input('是否继续 Y/N?')
    if keep_running.lower() == 'n':
        break

在这里插入图片描述

是否继续 Y/N?n
# 使用plotly模拟掷骰子
# 需要创建在浏览器显示的图表时,Plotly很有用,
# 它生成的图表时交互式的

# 创建一个表示骰子的类 die.py
# 掷骰子的可视化 die_visual.py

die.py

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)

die_visual.py

from plotly.graph_objs import Bar,Layout
from plotly import offline
from die import Die

# 创建一个D6
# 同时掷2枚骰子
die_1 = Die()
die_2 = Die(10)
# 掷几次骰子并将结果保存在一个列表中
results = []
for roll_num in range(10000):
    results.append(die_1.roll() + die_2.roll())

# print(results)
max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(x) for x in range(2,max_result+1)]
# print(frequencies)
# print(1/6)

# 对结果进行可视化
x_values = list(range(2,max_result+1))
data = [Bar(x=x_values,y=frequencies)]

x_axis_cofig = {
    'title':'结果','dtick':1}
y_axis_cofig = {
    'title':'结果的频率'}

my_layout=Layout(title="掷1个D6,一个D10 骰子 10000次的结果",
                 xaxis=x_axis_cofig,yaxis=y_axis_cofig)

offline.plot({
    'data':data,'layout' : my_layout}, filename='d6.html')


'd6.html'

在这里插入图片描述



ref: 《python编程从入门到实践》(第二版)
原网站

版权声明
本文为[Morbidmuse]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Morbidmuse/article/details/122341321