Python3 數據可視化之matplotlib、Pygal、requests

matplotlib的學習和使用

matplotlib的安裝

pip3 install matplotlib

簡單的折線圖

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.title("Square Number",fontsize=24) plt.xlabel("Value",fontsize=24) plt.ylabel("Square of Value",fontsize=14) #設置刻度標記的大小 plt.tick_params(axis='both',labelsize=14) #顯示圖表 plt.show() #保存在當前的目錄下,文件名爲squares_plot.png #plt.savefig('squares_plot.png', bbox_inches='tight')

這裏寫圖片描述

繪製簡單的散點圖

import matplotlib.pyplot as plt x_values = [1, 2, 3, 4, 5] y_values = [1, 4, 9, 16, 25] plt.scatter(x_values, y_values, s=100) #設置圖表的標題 並給座標軸加上標籤 plt.title("Square Number",fontsize=24) plt.xlabel("Value",fontsize=24) plt.ylabel("Square of Value",fontsize=14) #設置刻度標記的大小 plt.tick_params(axis='both',labelsize=14) plt.show()

這裏寫圖片描述

import  matplotlib.pyplot as plt

#繪製散點圖並設置其樣式 x_value = list(range(1,1001)) y_value = [x**2 for x in x_value] #點的顏色 c=(0,0,1,0.5) edgecolors = 'red' 點的邊緣顏色 plt.scatter(x_value,y_value,c=y_value,cmap=plt.cm.Blues,edgecolors='none',s=40) # plt.scatter(2,4,s=200) #設置圖表的標題 並給座標軸加上標籤 plt.title("Square Number",fontsize=24) plt.xlabel("Value",fontsize=24) plt.ylabel("Square of Value",fontsize=14) #設置刻度標記的大小 plt.tick_params(axis='both',labelsize=14) #設置每一個座標系的取值範圍 # plt.axis([0,110,0,110000]) #顯示 plt.show() #顯示並保存 #plt.savefig('pyplot_scatter.png',bbox_inches='tight')

這裏寫圖片描述

繪製隨機漫步圖

random_walk.pyhtml

from random import choice class RandomWalk(): """一個生成隨機漫步數據的類""" def __init__(self,num_points=5000): """一個生成隨機漫步的數據的類""" self.num_points = num_points; #全部的隨機漫步都始於(0,0) self.x_value = [0] self.y_value = [0] def fill_walk(self): """計算隨機漫步包含的點""" #不斷漫步,直到列表達到指定的長度 while len(self.x_value) < 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值 next_x = self.x_value[-1] + x_step next_y = self.y_value[-1] + y_step self.x_value.append(next_x) self.y_value.append(next_y)

rw_visual.pypython

import  matplotlib.pyplot as plt
#引用同級目錄下的文件 from Random_Walk.random_walk import RandomWalk #建立一個RandomWalk的實例 並將其包含的點都繪製出來 rw = RandomWalk() rw.fill_walk() print("test") point_numbers = list(range(rw.num_points)) plt.scatter(rw.x_value,rw.y_value,c=point_numbers, cmap=plt.cm.Blues,edgecolor='none',s=15) # 突出起點和終點 plt.scatter(0, 0, c='green',edgecolors='none',s=100) plt.scatter(rw.x_value[-1], rw.y_value[-1],c='red',edgecolors='none',s=100) # 設置繪圖窗口的尺寸 # plt.figure(figsize=(10, 6)) plt.figure(dpi=128, figsize=(10, 6)) # 隱藏座標軸 # plt.axes().get_xaxis().set_visible(False) # plt.axes().get_yaxis().set_visible(False) plt.show() 

Pygal的學習和使用

安裝Pygal

pip3 install pygal

繪製簡單的直方圖

建立骰子類 die.pygit

from random import randint class Die(): """表示一個骰子的類""" def __init__(self,num_sides=6): """骰子默認爲6面""" self.num_sides = num_sides def roll(self): """返回一個位於1和骰子面數之間的隨機值""" return randint(1,self.num_sides)

擲骰子die_visual.pygithub

from  Pygal_learn.die import Die import pygal #建立一個D6 die = Die() #擲幾回骰子 並將結果存儲在一個列表中 results = [] for roll_num in range(1000): result = die.roll() results.append(result) frequencies = [] #分析結果 for value in range(1,die.num_sides+1): frequency = results.count(value) frequencies.append(frequency) #對結果進行可視化 hist = pygal.Bar() hist.title = "Result 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") 

 

這裏寫圖片描述

使用Web API

安裝requests

pip3 install requests

繪製圖表

經過抓取GitHub上受歡迎程度最高的Python項目,繪製出圖表web

import  requests
import  pygal
from pygal.style  import  LightColorizedStyle as LCS,LightenStyle as LS

#執行API調用並存儲響應 url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' r = requests.get(url) print("Staus code:",r.status_code) response_dict = r.json() print("Total repositories:", response_dict['total_count']) #探索有關倉庫的信息 repo_dicts = response_dict['items'] print('Repositories returned:',len(repo_dicts)) #研究第一個倉庫 # repo_dict = repo_dicts[0] # for key in sorted(repo_dict.keys()): # print(key) #研究倉庫有關的信息 # Name: macOS-Security-and-Privacy-Guide # Owner: drduh # Stars: 12348 # Repository: https://github.com/drduh/macOS-Security-and-Privacy-Guide # Description: A practical guide to securing macOS. names,plot_dicts = [],[] for repo_dict in repo_dicts: names.append(repo_dict["name"]) # stars.append(repo_dict["stargazers_count"]) plot_dict = { 'value': repo_dict['stargazers_count'], 'label': str(repo_dict['description']), 'xlink': repo_dict['html_url'] } plot_dicts.append(plot_dict) #可視化數據 my_config = pygal.Config() my_config.x_label_rotation = 45 my_config.show_legend = False my_config.title_font_size = 24 my_config.label_font_size = 14 my_config.major_label_font_size = 18 my_config.truncate_label = 15 my_config.show_y_guides = False my_config.width = 1000 my_style = LS('#333366',base_style=LCS) chart = pygal.Bar(my_config,style=my_style) chart.title = "Most-Stared Python Project on Github" chart.x_labels = names print(plot_dicts) chart.add('',plot_dicts) chart.render_to_file('python_repos.svg')

這裏寫圖片描述

4 從json文件中提取數據,並進行可視化編程

4.1 數據來源:population_data.json。json

4.2 一個簡單的代碼段:api

  1. import json  #導入json模版  
  2. filename = 'population_data.png'  
  3. with open(filename) as f:  
  4.      pop_data = json.load(f)  #加載json文件數據  

經過小的代碼段瞭解最基本的原理,具體詳情還要去查看手冊。

 

4.3製做簡單的世界地圖(代碼以下)瀏覽器

  1. import pygal  #導入pygal  
  2.   
  3. wm = pygal.maps.world.World()  #正確導入世界地圖模塊  
  4. wm.title = 'populations of Countries in North America'  
  5. wm.add('North America',{'ca':34126000,'us':309349000,'mx':113423000})  
  6.   
  7. wm.render_to_file('na_populations.svg')  #生成svg文件  

結果:

 

4.4 製做世界地圖app

代碼段:

  1. import json  
  2.   
  3. import pygal  
  4. from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS  
  5.   
  6. from country_codes import get_country_code  
  7.   
  8. # Load the data into a list.  
  9. filename = 'population_data.json'  
  10. with open(filename) as f:  
  11.     pop_data = json.load(f)  
  12.   
  13. # Build a dictionary of population data.  
  14. cc_populations = {}  
  15. for pop_dict in pop_data:  
  16.     if pop_dict['Year'] == '2010':  
  17.         country_name = pop_dict['Country Name']  
  18.         population = int(float(pop_dict['Value']))  
  19.         code = get_country_code(country_name)  
  20.         if code:  
  21.             cc_populations[code] = population  
  22.   
  23. # Group the countries into 3 population levels.  
  24. cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}  
  25. for cc, pop in cc_populations.items():  
  26.     if pop < 10000000:                #分組  
  27.         cc_pops_1[cc] = pop  
  28.     elif pop < 1000000000:  
  29.         cc_pops_2[cc] = pop  
  30.     else:  
  31.         cc_pops_3[cc] = pop  
  32.   
  33. # See how many countries are in each level.          
  34. print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))  
  35.   
  36. wm_style = RS('#336699', base_style=LCS)  
  37. wm = pygal.maps.world.World(style=wm_style)   #已修改,原代碼有錯誤!  
  38. wm.title = 'World Population in 2010, by Country'  
  39. wm.add('0-10m', cc_pops_1)  
  40. wm.add('10m-1bn', cc_pops_2)  
  41. wm.add('>1bn', cc_pops_3)  
  42.       
  43. wm.render_to_file('world_population.svg')  

輔助代碼段country_code.py以下:

    1. from pygal.maps.world import COUNTRIES  
    2. from pygal_maps_world import i18n      #原代碼也有錯誤,現已訂正  
    3.   
    4. def get_country_code(country_name):  
    5.     """Return the Pygal 2-digit country code for the given country."""  
    6.     for code, name in COUNTRIES.items():  
    7.         if name == country_name:  
    8.             return code  
    9.     # If the country wasn't found, return None.  
    10.     return None  

監視API的速率限制

大多數API都存在速率限制,即你在特定時間內可執行的請求數存在限制。要獲悉你是否接近了GitHub的限制,請在瀏覽器中輸入https://api.github.com/rate_limit ,你將看到相似於下 面的響應:

這裏寫圖片描述

參考內容:《Python編程:從入門到實踐》

相關文章
相關標籤/搜索