美文网首页
Pythone入门到实践-学习笔记-Day6

Pythone入门到实践-学习笔记-Day6

作者: DKJImmy | 来源:发表于2018-03-28 14:59 被阅读0次

第十五章 生成数据

一、安装matplotlib

1、在https://dev.windows.com下载Visual Studio Community,并安装
2、cmd进入命令窗口,输入:pip install matplotlib回车,进入安装
3、验证安装结果

python
>>>import matplotlib
#没报错说明安装成功

二、绘制图表

绘制拆线图

import matplotlib.pyplot as plt

input_values = [1,2,3,4,5,6]
squares = [1,2,4,9,16]
#根据squeres绘制图形,linewidth线条加粗
plt.plot(input_values,squares,linewidth=5)
#设置标题和标题字号
plt.title("Squares",fontsize=24)
#x,y坐标标签
plt.xlabel('Value')
plt.ylabel('squares of value')

plt.tick_params(axis='both', labelsize=14)
#打开matplotlib查看器
plt.show()
运行结果

绘制拆散点图

import matplotlib.pyplot as plt

values = list(range(1,1001))
squares = [x**2 for x in values]
#scatter:绘制点
#s=10:点的大小
#c='red'自定义颜色,c=squeres,cmap=plt.cm.Blues渐变
#edgecolor='none':删除数据点的廓
plt.scatter(values,squares,c=squares, cmap=plt.cm.Blues,edgecolor='none',s=10)
plt.title("Squares",fontsize=24)
plt.xlabel('Value')
plt.ylabel('squares of value')
#axis():指定每个坐标的取值范围,分别x和y坐标最小值和最大值
plt.axis([0,1100,0,1100000])
#savefig():保存图表,第一实参保存路径和文件名,
#第二个实参将图表周围多余的空白区域剪掉,如果要你保留可省略
plt.savefig('squares.png',bbox_inches='tight')
plt.show()
运行结果

随机漫步

import matplotlib.pyplot as plt
from random import choice

class RandomWalk():
    def __init__(self, num_points = 5000):
        self.num_points = num_points
        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

            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()
    #设置绘图窗口尺寸
    #figure()用于指定图表的宽度、高度(单位英寸)、分辨率和背景色
    plt.figure(figsize=(10,6))
    num_points = list(range(rw.num_points))    
    plt.scatter(rw.x_values,rw.y_values,c=num_points,cmap=plt.cm.Blues,s=3)
    #使用拆线图绘制
    #plt.plot(rw.x_values,rw.y_values,linewidth=5)

    #绘制起点和终点
    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)
    #隐藏坐标
    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模拟掷骰子

Pygal(可视化包)生成可缩放的矢量图形文件,可在不同尺寸的屏幕上自动缩放图表

from random import randint
import pygal

class Die():
    def __init__(self,num_sides = 6):
        self.num_sides = 6
    def roll(self):
        return randint(1,self.num_sides)

die = Die()
results = []
#1000次投掷结果
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

#分析每个点数出现次数
frequencies = []
for value in range(1,die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)
    
print(frequencies)

#显示直方图
hist = pygal.Bar()

hist.title = 'Result of rolling one D6 1000 times'
hist.x_label = [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.svg')
运行结果

相关文章

网友评论

      本文标题:Pythone入门到实践-学习笔记-Day6

      本文链接:https://www.haomeiwen.com/subject/bdlscftx.html