Python數據可視化
寫得比較粗淺,后面會對數據分析專題進行深入。
安裝環境matplotlib
個人前面也說了強烈建議使用Pycharm作為Python初學者的首選IDE,主要還是因為其強大的插件功能,很多環境都能一鍵安裝完成,像本文的matplotlib,numpy,requests等。
下面直接上效果圖:
繪制簡單的折絲圖
使用plot來繪制折線
import matplotlib.pyplot as plt
# 繪制折線圖
squares = [1, 4, 9, 16, 25]
# plt.plot(squares, linewidth=5) # 指定折線粗細,
# #plt.show();
#
# #修改標簽文字和線條粗細
# plt.title("squre number", fontsize=24)
# plt.xlabel("Value", fontsize=14)
# plt.ylabel("square of value", fontsize=14)
# plt.tick_params(axis='both', labelsize=14)
# plt.show()
# 校正圖形
input_values = [1, 2, 3, 4, 5]
plt.plot(input_values, squares, linewidth=5)
plt.show()
折線圖1.png
生成的效果圖:
使用scatter繪制散點圖并設置樣式
import matplotlib.pyplot as plt
# 簡單的點
# plt.scatter(2, 4)
# plt.show()
#
# # 修改標簽文字和線條粗細
plt.title("squre number", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("square of value", fontsize=14)
#設置刻度標記大小
plt.tick_params(axis='both', which='major', labelsize=14)
# 繪制散點
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, s=100)
plt.show()
scatter繪制散點.png
自動計算數據
import matplotlib.pyplot as plt
x_values = list(range(1, 1001))
y_values = [x ** 2 for x in x_values]
# y_values = [x * x for x in x_values]
# y_values = [x ^ 2 for x in x_values]
plt.scatter(x_values, y_values, s=40)
# 坐標軸的取值范圍
# plt.axis(0, 1100, 0, 1100000) # 依次是xmin xmax,ymin,ymax
plt.show()
自動計算效果圖.png
隨機漫步
import matplotlib.pyplot as ply
from random import choice
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
# 不斷走,直到達到指定步數
while len(self.x_values) < self.num_points:
# 決定前進方向以及沿這個方向前進的距離
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y_step = y_direction * y_distance
# 不能原地踏步
if x_step == 0 and y_step == 0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
rw = RandomWalk()
rw.fill_walk()
ply.scatter(rw.x_values, rw.y_values, s=15)
ply.show()
效果圖
隨機漫步圖.png
使用Pygal模擬擲骰子
pygal能夠繪制的圖形可以訪問pygal介紹
pygal繪圖.png
環境安裝,直接在Pycharm上安裝插件。
import pygal
from random import randint
class Die():
def __init__(self, num_sides=6):
self.num_sides = num_sides;
def roll(self):
# 返回一個位于1和骰子面數之間的隨機值
return randint(1, self.num_sides)
die = Die()
results = []
# 擲100次骰子,并將結果放在列表中。
for roll_num in range(10):
result = die.roll()
results.append(str(result))
print(results)
# 分析結果
frequencies = []
for value in range(1, die.num_sides + 1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
# 對結果進行可視化
hist = pygal.Box()
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
1.1安裝requests
這個可以直接在Pycharm中安裝插件,非常方便。
1.2處理API響應
import requests
# 執行api調用并存儲響應
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
# 將api響應存儲在一個變量中
response_dic = r.json()
# 處理結果
print(response_dic.keys())
得到結果:
Status code: 200
dict_keys(['total_count', 'incomplete_results', 'items'])
1.3處理響應字典
# 將api響應存儲在一個變量中
response_dic = r.json()
# 處理結果
print(response_dic.keys())
print("Total repositories:", response_dic['total_count'])
repo_dics = response_dic['items']
print("repositories returned:" + str(len(repo_dics)))
# 研究一個倉庫
repo_dic = repo_dics[0]
print("\nKeys:", str(len(repo_dic)))
# for key in sorted(repo_dic.keys()):
# print(key)
print("Name:", repo_dic['name'])
print("Owner:", repo_dic['owner']['login'])
print("Starts:", repo_dic['stargazers_count'])
print("Repository:", repo_dic['html_url'])
print("Created:", repo_dic['created_at'])
print("Updated:", repo_dic['updated_at'])
print("Description:", repo_dic['description'])
得到結果:
Total repositories: 2061622
repositories returned:30
Keys: 71
Name: awesome-python
Owner: vinta
Starts: 40294
Repository: https://github.com/vinta/awesome-python
Created: 2014-06-27T21:00:06Z
Updated: 2017-10-29T00:50:49Z
Description: A curated list of awesome Python frameworks, libraries, software and resources