天天看點

Python3 資料可視化之matplotlib、Pygal、requests

matplotlib的學習和使用

matplotlib的安裝

pip3 install matplotlib
           

簡單的折線圖

import  matplotlib.pyplot as plt
#繪制簡單的圖表
input_values = [,,,,]
squares = [,,,,]
plt.plot(input_values,squares,linewidth=)

#設定圖表的标題 并給坐标軸加上标簽
plt.title("Square Number",fontsize=)
plt.xlabel("Value",fontsize=)
plt.ylabel("Square of Value",fontsize=)

#設定刻度标記的大小
plt.tick_params(axis='both',labelsize=)
#顯示圖表
plt.show()
#儲存在目前的目錄下,檔案名為squares_plot.png
#plt.savefig('squares_plot.png', bbox_inches='tight')
           
Python3 資料可視化之matplotlib、Pygal、requests

繪制簡單的散點圖

import matplotlib.pyplot as plt

x_values = [, , , , ]
y_values = [, , , , ]

plt.scatter(x_values, y_values, s=)

#設定圖表的标題 并給坐标軸加上标簽
plt.title("Square Number",fontsize=)
plt.xlabel("Value",fontsize=)
plt.ylabel("Square of Value",fontsize=)

#設定刻度标記的大小
plt.tick_params(axis='both',labelsize=)

plt.show()
           
Python3 資料可視化之matplotlib、Pygal、requests
import  matplotlib.pyplot as plt

#繪制散點圖并設定其樣式

x_value = list(range(,))
y_value = [x** 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=)
# plt.scatter(2,4,s=200)

#設定圖表的标題 并給坐标軸加上标簽
plt.title("Square Number",fontsize=)
plt.xlabel("Value",fontsize=)
plt.ylabel("Square of Value",fontsize=)

#設定刻度标記的大小
plt.tick_params(axis='both',labelsize=)

#設定每個坐标系的取值範圍
# plt.axis([0,110,0,110000])


#顯示
plt.show()
#顯示并儲存
#plt.savefig('pyplot_scatter.png',bbox_inches='tight')
           
Python3 資料可視化之matplotlib、Pygal、requests

繪制随機漫步圖

random_walk.py

from  random import choice

class RandomWalk():
    """一個生成随機漫步資料的類"""

    def __init__(self,num_points=):
        """一個生成随機漫步的資料的類"""
        self.num_points = num_points;
        #所有的随機漫步都始于(0,0)
        self.x_value = []
        self.y_value = []

    def fill_walk(self):
        """計算随機漫步包含的點"""

        #不斷漫步,直到清單達到指定的長度
        while len(self.x_value) < self.num_points:
            #決定前進的方向以及沿這個方向前進的距離
            x_direction= choice([,-])
            x_distance = choice([,,,,])
            x_step = x_direction*x_distance



            y_direction = choice([,-])
            y_distance = choice([, , , , ])
            y_step = y_direction * y_distance

            #拒絕原地踏步
            if x_step ==  and y_step == :
                continue

            #計算下一個點的x和y值
            next_x = self.x_value[-] + x_step
            next_y = self.y_value[-] + y_step

            self.x_value.append(next_x)
            self.y_value.append(next_y)
           

rw_visual.py

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=)
# 突出起點和終點
plt.scatter(, , c='green',edgecolors='none',s=)
plt.scatter(rw.x_value[-], rw.y_value[-],c='red',edgecolors='none',s=)

# 設定繪圖視窗的尺寸
# plt.figure(figsize=(10, 6))
plt.figure(dpi=, figsize=(, ))

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


plt.show()

           

Pygal的學習和使用

安裝Pygal

pip3 install pygal
           

繪制簡單的直方圖

建立骰子類 die.py

from  random import  randint

class Die():

    """表示一個骰子的類"""
    def __init__(self,num_sides=):
        """骰子預設為6面"""
        self.num_sides = num_sides


    def roll(self):
        """傳回一個位于1和骰子面數之間的随機值"""
        return  randint(,self.num_sides)
           

擲骰子die_visual.py

from  Pygal_learn.die import  Die
import  pygal
#建立一個D6
die = Die()

#擲幾次骰子 并将結果存儲在一個清單中
results = []
for roll_num in range():
    result = die.roll()
    results.append(result)


frequencies = []
#分析結果
for value in range(,die.num_sides+):
    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")

           
Python3 資料可視化之matplotlib、Pygal、requests

使用Web API

安裝requests

pip3 install requests
           

繪制圖表

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

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 = 
my_config.show_legend = False
my_config.title_font_size = 
my_config.label_font_size = 
my_config.major_label_font_size = 
my_config.truncate_label = 
my_config.show_y_guides = False
my_config.width = 

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')
           
Python3 資料可視化之matplotlib、Pygal、requests

監視API的速率限制

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

Python3 資料可視化之matplotlib、Pygal、requests

參考内容:《Python程式設計:從入門到實踐》