Python數(shù)據(jù)可視化
寫得比較粗淺寸潦,后面會(huì)對(duì)數(shù)據(jù)分析專題進(jìn)行深入杈笔。
安裝環(huán)境matplotlib
個(gè)人前面也說了強(qiáng)烈建議使用Pycharm作為Python初學(xué)者的首選IDE,主要還是因?yàn)槠鋸?qiáng)大的插件功能留储,很多環(huán)境都能一鍵安裝完成,像本文的matplotlib,numpy,requests等缘滥。
下面直接上效果圖:
繪制簡(jiǎn)單的折絲圖
使用plot來繪制折線
import matplotlib.pyplot as plt
# 繪制折線圖
squares = [1, 4, 9, 16, 25]
# plt.plot(squares, linewidth=5) # 指定折線粗細(xì),
# #plt.show();
#
# #修改標(biāo)簽文字和線條粗細(xì)
# 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()
生成的效果圖:
使用scatter繪制散點(diǎn)圖并設(shè)置樣式
import matplotlib.pyplot as plt
# 簡(jiǎn)單的點(diǎn)
# plt.scatter(2, 4)
# plt.show()
#
# # 修改標(biāo)簽文字和線條粗細(xì)
plt.title("squre number", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("square of value", fontsize=14)
#設(shè)置刻度標(biāo)記大小
plt.tick_params(axis='both', which='major', labelsize=14)
# 繪制散點(diǎn)
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, s=100)
plt.show()
自動(dòng)計(jì)算數(shù)據(jù)
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)
# 坐標(biāo)軸的取值范圍
# plt.axis(0, 1100, 0, 1100000) # 依次是xmin xmax,ymin,ymax
plt.show()
隨機(jī)漫步
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):
# 不斷走谒主,直到達(dá)到指定步數(shù)
while len(self.x_values) < self.num_points:
# 決定前進(jìn)方向以及沿這個(gè)方向前進(jìn)的距離
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()
效果圖
使用Pygal模擬擲骰子
pygal能夠繪制的圖形可以訪問pygal介紹
環(huán)境安裝朝扼,直接在Pycharm上安裝插件。
import pygal
from random import randint
class Die():
def __init__(self, num_sides=6):
self.num_sides = num_sides;
def roll(self):
# 返回一個(gè)位于1和骰子面數(shù)之間的隨機(jī)值
return randint(1, self.num_sides)
die = Die()
results = []
# 擲100次骰子霎肯,并將結(jié)果放在列表中擎颖。
for roll_num in range(10):
result = die.roll()
results.append(str(result))
print(results)
# 分析結(jié)果
frequencies = []
for value in range(1, die.num_sides + 1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
# 對(duì)結(jié)果進(jìn)行可視化
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
這個(gè)可以直接在Pycharm中安裝插件,非常方便观游。
1.2處理API響應(yīng)
import requests
# 執(zhí)行api調(diào)用并存儲(chǔ)響應(yīng)
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
# 將api響應(yīng)存儲(chǔ)在一個(gè)變量中
response_dic = r.json()
# 處理結(jié)果
print(response_dic.keys())
得到結(jié)果:
Status code: 200
dict_keys(['total_count', 'incomplete_results', 'items'])
1.3處理響應(yīng)字典
# 將api響應(yīng)存儲(chǔ)在一個(gè)變量中
response_dic = r.json()
# 處理結(jié)果
print(response_dic.keys())
print("Total repositories:", response_dic['total_count'])
repo_dics = response_dic['items']
print("repositories returned:" + str(len(repo_dics)))
# 研究一個(gè)倉(cāng)庫(kù)
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'])
得到結(jié)果:
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