python编程-- 从0到1绘制数据

本文介绍了Python编程中的数据可视化,包括绘制简单折线图、散点图,详细讲解了如何设置坐标轴范围,改变点的颜色,以及自动保存图表。还探讨了随机漫步的概念,并展示了创建渐变色的随机漫步图。最后提到了pygal库,特别是roll one dice功能。

绘制简单的折线图

首先下载matplotlib安装程序

import matplotlib.pyplot as plt

x_values = [1, 2, 3, 4, 5, 6]  # 代表x轴的值
y_values = [1, 2, 4, 8, 16, 32]  # 代表与x相对应的y轴的值
# plt.plot(y_values, linewidth=3)
plt.plot(x_values, y_values, linewidth=3)

# 设置图表标题,并改变横纵坐标的名称
plt.title("figure test", fontsize=24)
plt.xlabel("xValue", fontsize=14)
plt.ylabel("yValue", fontsize=14)

# 更改刻度标记的大小
plt.tick_params(axis='both', labelsize=12)

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

在这里插入图片描述

散点图

import matplotlib.pyplot as plt

# 绘制单个x = 2, y = 4坐标轴上的点
# plt.scatter(2, 4, s=100)  # s用来更改单个点的大小

# 绘制一群点
x_values = [1, 2, 3, 4, 5]
y_values = [1, 2, 4, 8, 16]
plt.scatter(x_values, y_values, s=100)

# 设置图表标题,并改变横纵坐标的名称
plt.title("figure test", fontsize=24)
plt.xlabel("xValue", fontsize=14)
plt.ylabel("yValue", fontsize=14)

# 更改刻度标记的大小
plt.tick_params(axis='both', which = 'major', labelsize=12)

plt.show()

在这里插入图片描述
另一种方法绘制此图:(自动生成数据)

import matplotlib.pyplot as plt

# 绘制单个x = 2, y = 4坐标轴上的点
# plt.scatter(2, 4, s=100)  # s用来更改单个点的大小

# 绘制一群点
i = 1
x_values = list(range(1, 6))
y_values = [2**(i-1) for i in x_values]

plt.scatter(x_values, y_values, s=100)

# 设置图表标题,并改变横纵坐标的名称
plt.title("figure test", fontsize=24)
plt.xlabel("xValue", fontsize=14)
plt.ylabel("yValue", fontsize=14)

# 更改刻度标记的大小
plt.tick_params(axis='both', which='major', labelsize=12)

plt.show()

设置每个坐标轴的取值范围

plt.axis([0, 100, 0, 1000]) 

前面对应x, 后面对应y
在这里插入图片描述

将主点颜色改成白,边缘颜色为红

plt.scatter(x_values, y_values, c='white', edgecolor='red', s=20)
plt.scatter(x_values, y_values, c=(1, 1, 1), edgecolor='red', s=20)

c for color; 含三个0~1之间的小数值

颜色映射(colormap)

plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Reds,
edgecolor='none', s=40)

要了解pyplot中所有的颜色映射: https://matplotlib.org/gallery/color/colormap_reference.html#sphx-glr-gallery-color-colormap-reference-py

自动保存图表

plt.savefig(‘Figure1.png’, bbox_inches=‘tight’)
第一个参数表示名字, 将其以Figure1.png存储在example.py同一个文件夹里
第二个参数表示将图表多余的空白区域裁剪掉

随机漫步

随机游走(random walk)也称随机漫步,随机行走等是指基于过去的表现,无法预测将来的发展步骤和方向。核心概念是指任何无规则行走者所带的守恒量都各自对应着一个扩散运输定律 ,接近于布朗运动,是布朗运动理想的数学状态,现阶段主要应用于互联网链接分析及金融股票市场中。(来自百度百科)

import matplotlib.pyplot as plt
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 start_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([-1, 1])
            x_distance = choice([0, 1, 2])
            x_walk = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 10, 20])
            y_walk = y_direction * y_distance

            # 拒绝原地不动
            if x_walk == 0 and y_walk == 0:
                continue

            # 计算下一个点的x和y值
            next_x = self.x_values[-1] + x_walk  # 从x_values的倒数第一个开始加上x方向走的距离
            next_y = self.y_values[-1] + y_walk  # 从y_values的倒数第一个开始加上y方向走的距离
            self.x_values.append(next_x)
            self.y_values.append(next_y)



randomwalk = RandomWalk()
randomwalk.start_walk()
plt.scatter(randomwalk.x_values, randomwalk.y_values, s=5)
plt.show()

在这里插入图片描述

随机漫步渐变色

randomwalk = RandomWalk()
randomwalk.start_walk()

point_numbers = list(range(randomwalk.num_points))
plt.scatter(randomwalk.x_values, randomwalk.y_values, c=point_numbers, cmap=plt.cm.Reds, edgecolor='none', s=5)

plt.show()

在这里插入图片描述

小知识点

绘制起点和终点

randomwalk = RandomWalk()
randomwalk.start_walk()

point_numbers = list(range(randomwalk.num_points))
plt.scatter(randomwalk.x_values, randomwalk.y_values, c=point_numbers, cmap=plt.cm.Reds, edgecolor='none', s=5)

# 绘制起点和终点
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(randomwalk.x_values[-1], randomwalk.y_values[-1], c='red', edgecolors='none', s=100)

plt.show()

在这里插入图片描述

画布尺寸

plt.figure(dpi=128, figsize=(10, 6))
单位为英寸;函数figure()用于指定图表的宽度、高度、分辨率和背景色。
dpi: 传递分辨率

隐藏坐标轴

plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

pygal

http://www.pygal.org/en/stable/documentation/types/index.html

roll one dice

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 = []

# 掷100次骰子
for roll_num in range(100):
    result = die.roll()
    results.append(result)

frequencies = []
for value in range(1, die.num_sides + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

horizontal_bar_chart = pygal.Bar()
horizontal_bar_chart.title = "randomly roll a 6-side die"

horizontal_bar_chart.x_labels = ['1', '2', '3', '4', '5', '6']
horizontal_bar_chart.x_title = "Result"
horizontal_bar_chart.y_title = "Frequency"

horizontal_bar_chart.add('6side', frequencies)
horizontal_bar_chart.render_to_file('die_visual.svg')

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值