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()
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")
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
4.3製做簡單的世界地圖(代碼以下)瀏覽器
4.4 製做世界地圖app
代碼段:
大多數API都存在速率限制,即你在特定時間內可執行的請求數存在限制。要獲悉你是否接近了GitHub的限制,請在瀏覽器中輸入https://api.github.com/rate_limit ,你將看到相似於下 面的響應: