好记性不如烂笔头

数据可视化(1)-生成数据

Posted on By ZealerDrm

如需转载本网站内容,请标明转载来源,且保持作品完整性

简单折线图

import matplotlib.pylab as plt
import math
import numpy

s = [1, 4, 9, 16, 25]
i = [1, 2, 3, 4, 5]
plt.plot(i, s, linewidth=5) # 设置线的长短
plt.title("Square Number", fontsize=25)
plt.xlabel("Value", fontsize=14)
plt.ylabel("S of Value", fontsize=10)

# 设置刻度标记的大小
plt.tick_params(axis="x", labelsize=15)
plt.show()

a = [1,2,3,4,5]
b = [1,2,3,4,5]
plt.scatter(a,b,s=100) # 设置点的大小
plt.title("scatter()", fontsize=25)
plt.xlabel("Value", fontsize=15)
plt.ylabel("Square of Value", fontsize=10)
plt.tick_params(axis="x", which="major", labelsize=15)
plt.show()


a = list(range(1, 100))
b = [i**2 for i in a]
plt.scatter(a, b, c='none', edgecolors=(1, 1, 0), s=10)  # 设置点的大小
plt.title("scatter()", fontsize=25)
plt.xlabel("Value", fontsize=15)
plt.ylabel("Square of Value", fontsize=10)
plt.tick_params(axis="both", which="major", labelsize=10)
plt.axis([0, 102, 0, 10500])
plt.show()


a = list(numpy.arange(0, 10, 0.001))
b = [math.sin(i) for i in a]
plt.scatter(a, b, c=b, cmap=plt.cm.Blues, edgecolors='none', s=10)  # 设置点的大小
plt.title("scatter()", fontsize=25)
plt.xlabel("Value", fontsize=15)
plt.ylabel("Square of Value", fontsize=10)
plt.tick_params(axis="both", which="major", labelsize=10)
plt.axis([0, 11, -1, 1])
plt.show()




a = list(numpy.arange(0, 10, 0.001))
b = [math.sin(i) for i in a]
plt.scatter(a, b, c=b, cmap=plt.cm.Blues, edgecolors='none', s=10)  # 设置点的大小
plt.title("scatter()", fontsize=25)
plt.xlabel("Value", fontsize=15)
plt.ylabel("Square of Value", fontsize=10)
plt.tick_params(axis="both", which="major", labelsize=10)
plt.axis([0, 11, -1, 1])
#保存图片,目录是在当前.py文件目录,第一个参数是文件名,第二个参数指定将多余空白区域剪掉。
plt.savefig('square_plot.png', bbox_inches='tight')

随机漫步图


from random import choice
import matplotlib.pyplot as plt


class RandomWalk():

    """一个生成随机漫步数据的类"""

    def __init__(self, num_points):
        """初始化随机漫步的属性"""
        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

            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)
        print(len(self.x_values))
        print(len(self.y_values))


while True:
    rw = RandomWalk(100000)
    rw.fill_walk()
    # 设置绘图窗口的尺寸,单位是英寸
    plt.figure(figsize=(10, 6))

    # 根据Y值大小渐变
    # plt.scatter(rw.x_values, rw.y_values, c=rw.y_values, cmap=plt.cm.Blues, edgecolors='none', s=10)

    # 突出起点和终点
    # 根据漫步点的先后渐变
    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.scatter(rw.x_values, rw.y_values, c=list(range(rw.num_points)), cmap=plt.cm.Blues, edgecolors='none', s=1)

    # 隐藏坐标轴
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    # 保存图片(需要放到.show()前)
    plt.savefig('manbu.png')
    plt.show()
    keep_running = input("Make another walk?(y/n):")
    if keep_running == 'n':
        break

由于类可以起到模板的作用,因此, 可以在创建实例的时候,把一些我们认为必须绑定的 属性强制填写进去。以学生类为例,通过定义一个特殊的

__init__方法,在创建实例的时候,就把name,score等属性绑上去:

class Student(object): 
	def __init__(self, name, score):
    self.name = name
    self.score = score 

注意:特殊方法“init”前后分别有两个下划线!!! 注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。

有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数(除非给init函数的形参直接赋值),但self不需要传,Python解释器自己会把实例变量传进去:

和普通的函数相比,在类中定义的函数只有一点不同, 就是第一个参数永远是实例变量self,并且, 调用时,不用传递该参数。除此之外,

类的方法和普通函数没有什么区别, 所以,你仍然可以用默认参数、可变参数、 关键字参数和命名关键字参数。

 >>> bart = Student('Bart Simpson', 59)
 >>> bart.name 
 'Bart Simpson'
 >>> bart.score 
 59

简单柱状图

from random import randint
import pygal


class Die():
    def __init__(self, num_sides = 6):
        self.num_sides = num_sides

    def roll(self):
        """返回一个位于1和骰子面数之间的随机值"""
        return randint(1, self.num_sides)


die = Die()
results = []
results1 = []
frequencies = []

# 随机生成N次结果(用两枚筛子)
for roll_num in range(1000):
    results.append(die.roll())
    results1.append(die.roll())
# 两枚筛子加起来
for i in range(1000):
    results[i] = results[i] + results1[i]
print(results)

# 统计每个面被摇到的次数
for value in range(1, die.num_sides * 2+1):
    frequencies.append(results.count(value))

hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
hist.x_title = "Result"
hist.y_title = "Frequencies"
hist.add('D6(2)', frequencies)
hist.render_to_file('die_visual.svg')