數據可視化:CSV格式,JSON格式


下載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()

下載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')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM