1. 程式人生 > >資料視覺化:CSV格式,JSON格式

資料視覺化:CSV格式,JSON格式

1、下載CSV格式資料,進行視覺化

csv.reader()建立一個與檔案有關聯的閱讀器(reader)物件,reader處理檔案中的第一行資料,並將每一項資料都儲存在列表中
head_row = next(reader) 返回檔案的下一行,CSV檔案第一行為標頭檔案
datetime.strptime(row[0], '%Y-%m-%d-%H-%M-%S') 將字串'2018-2-15-13-35-1'轉換為一個表示日期時間的物件
plt.text() 給圖表添加註釋,其中%.nf其中n表示顯示小數後面幾位,%b表示只標註y
plt.annotate() 引數xytext表示偏移距離,%b表示只標註y
fill_between()接受一個x值系列和兩個Y值系列,並填充兩個y值系列之間的空間,引數alpha值代表顏色透明度,預設1
      引數
facecolor代表填充顏色
from datetime import datetime
import matplotlib.pyplot as plt
import csv
import numpy as np
with open('csv_file\photo.csv') as f_obj:
    reader = csv.reader(f_obj)
    dates,heights_1,heights_2 = [],[],[]
    
for row in reader: try: height_1 = float(row[3])#將字串轉換為浮點型 height_2 = float(row[4]) # 將字串'2018-2-15-13-35-1'轉換為一個表示日期時間的物件 date = datetime.strptime(row[0], '%Y-%m-%d-%H-%M-%S') except ValueError: #如果有哪一天的資料缺失,列印缺失日期 print(date,'
missing data.') else: # 將所有高程插入列表 dates.append(date) heights_1.append(height_1) heights_2.append(height_2) fig = plt.figure(figsize=(12,8)) plt.tick_params(axis='both',labelsize=14) #為防止x軸標籤重疊,讓日期型的x軸標籤自動展現 fig.autofmt_xdate(rotation=45) #在同一個視窗中繪製兩條折線 x = np.array(dates) y = np.array(heights_1) for a,b in zip(x,y): #用text()標註,%.nf其中n表示顯示小數後面幾位,%b表示只標註y plt.text(a,b+0.1,'%.2f'%b,ha = 'center',va = 'bottom', fontsize=8) #用annotate()標註,xytext表示偏移距離,%b表示只標註y #plt.annotate('%s'%b,xy=(a,b),xytext=(-20,10), #textcoords='offset points',fontsize=8) plt.plot(dates,heights_1,linewidth=3,c='c') x = np.array(dates) y = np.array(heights_2) for a,b in zip(x,y): plt.text(a, b + 0.1, '%.2f' % b, ha='center', va='bottom', fontsize=8) plt.plot(dates,heights_2,linewidth=3,c='red') #fill_between()接受一個x值系列和兩個Y值系列,並填充兩個y值系列之間的空間 plt.fill_between(dates,heights_1,heights_2,facecolor='greenyellow', alpha=0.3)#alpha值代表顏色透明度,預設1 plt.show()

2、下載JSON格式檔案視覺化 

import json --讀取,寫入json檔案

from pygal.style import RotateStyle,LightColorizedStyle,LightenStyle --定義地圖樣式

import pygal_maps_world.maps (import pygal.maps.world也可以)

from pygal_maps_world.i18n import COUNTRIES -- 獲取兩位國別碼和國家名

wm=pygal_maps_world.maps.World() --定義一個世界地圖例項

南北美洲所有國家的國別碼:
wm.add('North America',['ca','mx','us'])
wm.add('Central America',['bz','cr','gt','hn','ni','pa','sv'])
wm.add('South America',['ar','bo','br','cl','co','ec','gf',
            'gy','pe','py','sr','uy','ve'])

 

Pygal樣式儲存在模組style中:
RotateStyle:修改風格(通過調整指定顏色建立樣式)
LightenStyle:輕盈風格(通過賦予特定的色彩來營造風格)
DarkenStyle:黑暗風格(通過使給定顏色變暗建立樣式)
SaturateStyle:飽和風格(通過飽和給定顏色建立樣式)
DesaturateStyle:去飽和風格(通過淡化給定顏色建立樣式)
LightColorizedStyle:加亮顏色(通過加亮給定顏色建立樣式)

RotateStyle('#336699')給三個分組調整顏色,十六進位制的RGB顏色是一個以#開頭的
字串,後面6個字元分別表示紅綠藍三個顏色佔的分量;hex color chooser-十六進位制
顏色選擇器;LightColorizedStyle 此類可單獨使用,加亮地圖顏色(包括整個圖表的主題)
同時也可以放在RotateStyl()函式中傳給實參base_style

 

import json
from pygal.style import RotateStyle,LightColorizedStyle
#import pygal.maps.world
import pygal_maps_world.maps
from pygal_maps_world.i18n import COUNTRIES
#定義一個獲取兩位國別碼的函式
def get_country_code(country_name):
    for code,name in COUNTRIES.items():
        if name == country_name:
            return code
    return None
filename = 'json_file\population_data.json'
with open(filename) as f:
    #將檔案中的字典儲存到列表中
    pop_data = json.load(f)
#將每個國家2010年的人口資料加入字典
cc_populations = {}
for pop_dict in pop_data:
    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
            #print(code + ':' + str(population))
        else:
            print( 'Error - ' + country_name)
#將世界人口數量等級分為三組
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_populations),len(cc_pops_1),len(cc_pops_2),len(cc_pops_3))
wm_style = RotateStyle('#336699',base_style=LightColorizedStyle)
#wm = pygal.maps.world.World()
wm = pygal_maps_world.maps.World(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('images\world_population.svg')