Python学习(七)数据可视化

一、简介
安装matplotlib包,用来制作各种图表
1、绘制简单的折线图
实例1

import matplotlib.pyplot as plt

input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values, squares, linewidth = 5)
plt.show()

2、绘制点图
使用scatter()函数, 传递一对x和y坐标,能够在指定位置绘制一个点

import matplotlib.pyplot as plt

# plt.scatter(2,4,s = 200)
# #设置图表标题并给坐标轴加上标签
# plt.title("Square Numbers", fontsize = 24)
# plt.xlabel("Value", fontsize = 14)
# plt.ylabel("Square of Value", fontsize = 14)
# #设置刻度标记的大小
# plt.tick_params(axis='both', which='major', labelsize=14)
# plt.show()

#使用scatter绘制出一系列的点,分别给出各个点的x坐标和y坐标即可
#自动计算数据
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, 0,1100000])
plt.show()

二、随机漫步
每次行走完全随机没有明确的方向
1、首先创建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
            #计算下一个点的x和y值, 上一个点的x坐标和y坐标
            # (下标-1表示倒数第一个)加上现在需要移动的路程
            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)

2、根据获得的x坐标和y坐标的列表,来绘图

import matplotlib.pyplot as plt

from random_walk import RandomWalk

while True:
    #创建一个RandomWalk的实例,并将所有的点都模拟出来
    rw = RandomWalk(50000)
    rw.fill_walk()
    #设置绘图窗口的大小
    plt.figure(dpi=128, figsize=(10,6))
    #绘制出点
    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values, rw.y_values, c=point_numbers,cmap=plt.cm.Blues,edgecolor='none',s=1)
    #突出起点和终点
    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 模拟掷骰子的随机结果的统计直方图
1、创建骰子类
from random import randint

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

def roll(self):
    #返回一个1到6的随机值
    return randint(1, self.num_sides)

2、生成骰子的结果

import pygal
from die import Die

die = Die()
#掷几次骰子,并将结果存储在一个列表中
results = []
#从0开始到99,就是执行100次
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

3、统计骰子各个面出现的次数

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

4、对结果进行柱状图的可视化

#对结果进行可视化
#创建一个Bar实例
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', frequencies)
hist.render_to_file('die_visual.svg')

5、以上是对一个骰子的统计,现在统计两个骰子的使用

import pygal

from die import Die

die1 = Die()
die2 = Die()

#掷几次骰子,并将结果存储在一个列表中
results = []
#从0开始到999,就是执行1000次
for roll_num in range(1000):
    result = die1.roll()+die2.roll()
    results.append(result)

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

#对结果进行可视化
#创建一个Bar实例
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times."
hist.x_labels = ['2','3','4','5','6','7','8','9','10','11','12']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6+D6', frequencies)
hist.render_to_file('dice_visual.svg')

四、访问可视化两种常用的格式存储的数据(CSV和JSON)
CSV:数据以一系列逗号分隔的值
JSON:以键值对的形式存储
1、分析csv的文件头,打印文件头的信息,并依次读取每一行我们需要的值

import csv
from datetime import datetime
from matplotlib import pyplot as plt

#filename='sitka_weather_07-2014.csv'
filename='death_valley_2014.csv'
with open(filename) as f:
    #创建一个与该文件相关联的文件阅读器对象
    reader = csv.reader(f)
    #调用next方法获得文件中的一行
    header_row = next(reader)
    #print(header_row)
    #enumerate获取每个元素的索引和值
    # for index, column_header in enumerate(header_row):
    #     print(index, column_header)
    #从文件中获取最高气温
    dates,highs,lows = [],[],[]
    #上面的next(reader)已经读取了第一行了,下面从第二行开始读取
    #每次读取每一行的第二个值
    for row in reader:
        try:
            current_date = datetime.strptime(row[0], "%Y/%m/%d")
            high = int(row[1])
            low = int(row[3])
        except ValueError:
            print(current_date,"missing date")
        else:
            dates.append(current_date)
            highs.append(high)
            lows.append(low)

2、根据数据绘制折线图

#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates, highs, c='red',alpha=0.5)#数据点为红色
plt.plot(dates, lows, c='blue',alpha=0.5)
#传递了一个x值系列和两个y值系列
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)

#设置图形格式
plt.title("Daily high and low temperatures, July 2014", fontsize=24)
plt.xlabel('', fontsize=16)
#来制斜的日期标签
fig.autofmt_xdate()
plt.ylabel("Temperature (F)", fontsize = 16)
plt.tick_params(axis='both', which='major', labelsize=16)

plt.show()

五、制作世界人口地图JSON格式
1、下载JSON文件,加载JSON文件数据

import json
import pygal
from pygal.style import LightColorizedStyle,RotateStyle

from country_codes import get_country_code

#把数据加载到列表中
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

2、对pop_data列表进行筛选出2010年的各个国家的人口数,然后创建字典,并进行分组存放到各个符合人口要求的国家的字典中

#创建一个包含人口数量的字典
cc_populations = {}
for pop_dict in pop_data:
    #使用所有国家为2010年的人口数据
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        #字符串的浮点数不能直接转换为整型类型,要先转为浮点型在转为整型
        population = int(float(pop_dict['Value']))
        code = get_country_code(country_name)
        if code:
            cc_populations[code] = population
cc_pops_1, cc_pops_2, cc_pops_3 = {},{},{}
for cc,pop in cc_populations.items():
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop
#看看每组分别包含多少个国家
print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))

3、绘制世界地图

wm_style = RotateStyle('#336699', base_style=LightColorizedStyle)
wm = pygal.Worldmap(style=wm_style)
wm.title='World Population in 2010, by Country'
wm.add('0-10m',cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file('world_population.svg')

猜你喜欢

转载自blog.csdn.net/u_hcy2000/article/details/82620300