python生成数据

生成数据学习笔记


安装matplotlib

安装matplotlib—数学绘图库

绘制简单的折线图

  • pyplot模块—有许多显示图表的函数
    import matplotlib.pyplot as plt;
    squares = [1,4,9,16,25]
    plt.plot(squares)
    plt.show()
  • 修改标签文字和线条粗细
    import matplotlib.pyplot as plt
    squares = [1,4,9,16,25]
    plt.plot(squares,linewidth=5)
    plt.title("Squares Numbers",fontsize=24)
    plt.xlable("Value",fontsize=14)
    plt.ylable("Square of Value",fontsize=14)
    plt.tick_params(axis='both',labelsize=14)
    plt.show()

ps:axis–轴

  • 修正数据
plot(x,y,linewidth)
#x与y的数据一一对应形成正确图像

###绘制散点图

  • scatter()函数绘制单点与一系列点
    与pylot类似
    scatter(x,y,s)
  • 自动计算数据
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,s=40)
plt.axis([0,1100,1,1100000])
pli.show()
  • 颜色映射
    scatter(x,y,c=y_values,cmap=plt.cm.Blues,s)
    形成一条蓝色渐变色的曲线
  • 自动保存图表
    plt.savefig(“图片名字.格式”,bbox_inches=‘tight’)
    第一个实参指定指定以什么样的文件名保存在工程文件目录中
    第二个实参指定将图表多余的空白区域裁剪掉

###随机漫步
首先生成随机数据,再用matplotlib展示出来

  • 创建RandomWalk()类
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)
  • 绘制随机漫步图
import matplotlib.pyplot as plt
from random_walk import RandomWalk
rw=RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15,c='red')
plt.show()
  • 给点着色
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
    rw = RandomWalk()
    rw.fill_walk()
    #对应每一个点的颜色映射
    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values,rw.y_values,s=15,c=point_numbers,cmap=plt.cm.Blues)
    plt.show()
    keep_running = input("Make another walk?(y/n)")
    if keep_running =='n':
        break
  • 重新绘制起点与终点
#起点为绿色,终点为红色
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)
  • 调整尺寸以适合屏幕
#dpi为屏幕分辨率,figsize指定图片的宽度和高度
plt.figure(dpi=128,figsize=(10,6))

使用Pygal模拟掷骰子

  • windows安装Pygal

pip install --user pygal

  • 创建Die类可创建骰子实例
 from random import randint

class Die():
    def __init__(self,num_sides=6):
        self.num_sides=num_sides
    def roll(self):
    #函数randint()用来返回一个1和面数之间的随机数
        return randint(1,self.num_sides)
  • 掷骰子
from die import Die
die = Die()
results =[]
for roll_num in range(100):
    result = die.roll()
    results.append(result)
print(results)
  • 分析结果,绘制直方图
import pygal
from die import Die
die = Die()
results =[]
for roll_num in range(1000):
    result = die.roll()
    results.append(result)
 #分析结果
frequencys =[]
for value in range(1,die.num_sides+1):
    frequency=results.count(value)
    frequencys.append(frequency)
 #对结果进行可视化,创建一个pygal.Bar()实例
 #对hist的属性进行设置
hist =pygal.Bar()
hist.title="Results of rolling one D6 1000 times."
hist.x_labels=['1','2','3','4','5','6']
hist.x_title="Result"
hist.y_title="Frequency of Result"
 #给图表传递一系列值并指定标签
hist.add('D6',frequencys)
 #将图表渲染为一个SVG文件——可自动缩放以适合观看者的屏幕
hist.render_to_file('die_visual.svg')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值