開發(fā)系統(tǒng)和開發(fā)IDE
開發(fā)系統(tǒng): Ubuntu 16.0.4 LTS
開發(fā)IDE: Visual Studio Code 版本: 1.32.3
Python版本: Python3
依賴庫: pygame
資料《Python編程從入門到實踐》書籍
鏈接:https://pan.baidu.com/s/1USkqvL2dLU3Q9XplVaGQJg
提取碼:zoyc
GitHub:
https://github.com/lichangke/Python3_Project/tree/master/data_visual
相關(guān)第三方庫
matplotlib:https://matplotlib.org/
sudo apt-get install python3-matplotlib
pygal:http://www.pygal.org/en/stable/
pip install --user pygal
pip install pygal_maps_world 額外需安裝
matplotlib 隨機漫步
matplotlib 簡單使用扇住,訪問相關(guān)第三方庫中鏈接了解更多
目錄文件結(jié)構(gòu)
# | 文件名 | 內(nèi)容 |
---|---|---|
- | mpl_squares.py | 繪制折線圖 |
- | random_walk.py | Python來生成隨機漫步數(shù)據(jù) |
- | rw_visual.py | 循環(huán)生成隨機漫步數(shù)據(jù)并生成顯示圖像,需random_walk.py |
- | scatter_squares.py | 繪制散點圖 |
隨機漫步數(shù)據(jù)顯示圖像
mpl_squares.py
'''
@File : mpl_squares.py
@Time : 2019/04/06 16:45:51
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 繪制折線圖
'''
# here put the import lib
# 導(dǎo)入了模塊pyplot
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5] # X 軸數(shù)據(jù)
squares = [1, 4, 9, 16, 25] # Y 軸數(shù)據(jù)
'''
plot(*args[, scalex, scaley, data])
繪制 x y 坐標組成的線
'''
plt.plot(input_values, squares, linewidth=5)
# 設(shè)置圖表標題技潘, 并給坐標軸加上標簽
plt.title( "Square Numbers", fontsize = 24 )
plt.xlabel( "Value", fontsize = 14 )
plt.ylabel( "Square of Value", fontsize = 14 )
# 設(shè)置刻度標記的大小
plt.tick_params( axis = 'both', labelsize = 14 , colors = 'r' ) # axis 將參數(shù)應(yīng)用于哪個軸
plt.show()
'''
打開matplotlib查看器, 并顯示繪制的圖形
'''
random_walk.py
'''
@File : random_walk.py
@Time : 2019/04/06 17:39:26
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : Python來生成隨機漫步數(shù)據(jù)
'''
# here put the import lib
from random import choice
class RandomWalk():
"""一個生成隨機漫步數(shù)據(jù)的類"""
def __init__(self, num_points=5000):
"""初始化隨機漫步的屬性"""
self.num_points = num_points
# 所有隨機漫步都始于(0, 0)
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])
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_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_visual.py
'''
@File : rw_visual.py
@Time : 2019/04/07 00:56:52
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 循環(huán)生成隨機漫步數(shù)據(jù)并顯示
'''
# here put the import lib
import matplotlib.pyplot as plt
from random_walk import RandomWalk
# 只要程序處于活動狀態(tài)冯键, 就不斷地模擬隨機漫步
while True:
rw = RandomWalk(50000)
rw.fill_walk()
'''
figure([num, figsize, dpi, facecolor, ...])
Create a new figure.
figsize : (float, float), optional, default: None
width, height in inches. If not provided, defaults to rcParams["figure.figsize"] = [6.4, 4.8].
dpi : integer, optional, default: None
resolution of the figure. If not provided, defaults to rcParams["figure.dpi"] = 100.
'''
# 設(shè)置繪圖窗口的尺寸
plt.figure(figsize=(10, 6),dpi=128)
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, s=1, c=point_numbers,
cmap=plt.cm.Blues, edgecolor='none')
# 突出起點和終點
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1],
c='red', edgecolors='none', s=100)
'''
The Axes class The Axes contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system.
'''
# 隱藏坐標軸
plt.axes().get_xaxis().set_visible(False) # Return the XAxis instance.
plt.axes().get_yaxis().set_visible(False) # Return the YAxis instance.
plt.show()
keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
break
scatter_squares.py
'''
@File : scatter_squares.py
@Time : 2019/04/06 17:08:01
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 繪制散點圖
'''
# here put the import lib
import matplotlib.pyplot as plt
'''
scatter(x, y[, s, c, marker, cmap, norm, ...])
繪制x y 坐標的散點圖沥寥,并設(shè)置不同的 標記 大小 或 顏色等与境。
'''
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
color = ['r', 'g', 'b']
# s 標記大小 以磅為單位**2 c 顏色吟榴,序列或顏色序列
plt.scatter(x_values, y_values, s=100, c=color)
# 設(shè)置圖表標題并給坐標軸加上標簽
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 設(shè)置刻度標記的大小
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
# 循環(huán)繪制1000個點
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
'''
c : color, sequence, or sequence of color, optional
A single color format string.
A sequence of color specifications of length n.
A sequence of n numbers to be mapped to colors using cmap and norm. #使用cmap和norm映射到顏色的n個數(shù)字序列
A 2-D array in which the rows are RGB or RGBA.
cmap : Colormap, optional, default: None # cmap 告訴pyplot 使用哪個顏色映射
edgecolors : color or sequence of color, optional, default: 'face' # 邊框顏色
'''
plt.scatter(x_values, y_values, s=40, c=y_values, cmap=plt.cm.Blues, edgecolor='none')
# 設(shè)置圖表標題并給坐標軸加上標簽
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 設(shè)置刻度標記的大小
plt.tick_params(axis='both', which='major', labelsize=14)
'''
axis(*v, **kwargs)
獲取或設(shè)置某些軸屬性的便捷方法
xmin, xmax, ymin, ymax = axis()
xmin, xmax, ymin, ymax = axis(xmin, xmax, ymin, ymax)
xmin, xmax, ymin, ymax = axis(option)
xmin, xmax, ymin, ymax = axis(**kwargs)
'''
# 設(shè)置每個坐標軸的取值范圍
plt.axis([0, 1100, 0, 1100000])
plt.show()
pygal 模擬擲骰子
pygal 簡單使用,訪問相關(guān)第三方庫中鏈接了解更多
目錄文件結(jié)構(gòu)
# | 文件名 | 內(nèi)容 |
---|---|---|
- | die.py | 骰子類 |
- | die_visual.py | 模擬擲骰子并柱狀圖顯示點數(shù)出現(xiàn)次數(shù),需die.py |
- | die_visual.svg | 生成的svg操刀,可用瀏覽器打開 |
die_visual.svg
die.py
'''
@File : die.py
@Time : 2019/04/06 21:53:11
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 骰子類
'''
# here put the import lib
from random import randint
class Die():
"""表示一個骰子的類"""
def __init__(self, num_sides=6):
"""骰子默認為6面"""
self.num_sides = num_sides
def roll(self):
""""返回一個位于1和骰子面數(shù)之間的隨機值"""
return randint(1, self.num_sides)
'''
def randint(a, b)
Return random integer in range [a, b], including both end points.
'''
die_visual.py
'''
@File : die_visual.py
@Time : 2019/04/06 21:56:06
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 模擬擲骰子并柱狀圖顯示點數(shù)出現(xiàn)次數(shù)
'''
# here put the import lib
from die import Die
import pygal
# 創(chuàng)建兩個D6
die_1 = Die(8)
die_2 = Die(8)
# 擲幾次骰子, 并將結(jié)果存儲在一個列表中
results = []
for roll_num in range(50000):
result = die_1.roll()+die_2.roll()
results.append(result)
# 分析結(jié)果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)
# 對結(jié)果進行可視化
hist = pygal.Bar() # Basic simple bar graph:
hist.title = "Results of rolling a D8 and a D8 50,000 times."
x_labels = set()
for i in range(1,die_1.num_sides+1):
for j in range(1, die_2.num_sides+1):
x_label = i + j
x_labels.add(x_label)
print(x_labels)
hist.x_labels = list(x_labels)
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
# 使用add() 將一系列值添加到圖表中(向它傳遞要給添加的值指定的標簽婴洼, 還有一個列表骨坑, 其中包含將出現(xiàn)在圖表中的值) 。
hist.add('D8 + D8', frequencies)
hist.render_to_file('die_visual.svg') # 最后柬采, 我們將這個圖表渲染為一個SVG文件
matplotlib繪制溫度折線圖
對CSV文件格式的數(shù)據(jù)處理欢唾,通過matplotlib繪制CSV文件中溫度數(shù)據(jù)的折線圖
目錄文件結(jié)構(gòu)
# | 文件名 | 內(nèi)容 |
---|---|---|
- | highs_lows.py | 處理CSV文件數(shù)據(jù),matplotlib繪制最高溫度最低溫度折線圖 |
- | 其他.csv | csv格式的溫度數(shù)據(jù) |
最高溫度最低溫度折線圖
highs_lows.py
'''
@File : highs_lows.py
@Time : 2019/04/06 22:32:59
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 處理CSV文件數(shù)據(jù)粉捻,matplotlib繪制最高溫度最低溫度折線圖
'''
# here put the import lib
# c sv 模塊包含在Python標準庫中
import csv
from matplotlib import pyplot as plt
# 模塊datetime 處理日期
from datetime import datetime
# 從文件中獲取日期礁遣、 最高氣溫和最低氣溫
filename = 'death_valley_2014.csv'
with open(filename) as f:
# 創(chuàng)建一個與該文件相關(guān)聯(lián)的閱讀器(reader ) 對象
reader = csv.reader(f)
# 模塊csv 包含函數(shù)next() , 調(diào)用它并將閱讀器對象傳遞給它時肩刃, 它將返回文件中的下一行祟霍。 在前面的代碼中, 我們只調(diào)用了next() 一次盈包, 因此得到的是文件的第一行沸呐, 其中包含文件頭
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader: # 遍歷文件中余下的各行
try: # 錯誤檢查
current_date = datetime.strptime(row[0], "%Y-%m-%d") # '2014-7-1
high = int(row[1])
low = int(row[3])
except ValueError:
print(current_date, 'missing data')
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
# 根據(jù)數(shù)據(jù)繪制圖形
fig = plt.figure(dpi=123, figsize=(10, 6))
'''
plot(*args[, scalex, scaley, data])
Plot y versus x as lines and/or markers.
alpha: float Set the alpha value used for blending - not supported on all backends.
'''
plt.plot(dates, highs, c='red', alpha=0.5) # 繪制最高溫度
plt.plot(dates, lows, c='blue', alpha=0.5) # 繪制最低溫度
'''
fill_between(x, y1[, y2, where, ...])
Fill the area between two horizontal curves.
'''
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# 設(shè)置圖形的格式
plt.title("Daily high temperatures - 2014", fontsize=24)
plt.xlabel('', fontsize=16)
'''
autofmt_xdate(self, bottom=0.2, rotation=30, ha='right', which=None)
Date ticklabels often overlap, so it is useful to rotate them and right align them.
bottom : scalar
The bottom of the subplots for subplots_adjust().
rotation : angle in degrees
The rotation of the xtick labels.
ha : string
The horizontal alignment of the xticklabels.
which : {None, 'major', 'minor', 'both'}
Selects which ticklabels to rotate. Default is None which works the same as major.
'''
fig.autofmt_xdate()
title = "Daily high and low temperatures - 2014\nDeath Valley, CA"
plt.title(title, fontsize=24)
'''
tick_params([axis])
Change the appearance of ticks, tick labels, and gridlines. 更改刻度,刻度標簽和網(wǎng)格線的外觀
axis : {'x', 'y', 'both'}, optional
Which axis to apply the parameters to.
which : {'major', 'minor', 'both'}
Default is 'major'; apply arguments to which ticks.
'''
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()
pygal繪制世界人口地圖
對json文件格式的數(shù)據(jù)處理呢燥,通過pygal繪制世界人口地圖
目錄文件結(jié)構(gòu)
# | 文件名 | 內(nèi)容 |
---|---|---|
- | country_codes.py | 處理國家識別碼 |
- | population_data.json | json文件格式的數(shù)據(jù) |
- | world_population.py | 對json文件格式的數(shù)據(jù)處理崭添,通過pygal繪制世界人口地圖,需country_codes.py |
- | world_population.svg | 繪制生成的世界人口地圖 |
世界人口地圖
country_codes.py
'''
@File : countries.py
@Time : 2019/04/06 23:42:39
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 處理國家識別碼
'''
# here put the import lib
# from pygal.i18n import COUNTRIES 模塊已被遺棄 但是現(xiàn)在可以在 pygal_maps_world 插件中找到它 pip3 install pygal_maps_world
from pygal.maps.world import COUNTRIES
def get_country_code(country_name):
"""根據(jù)指定的國家叛氨, 返回Pygal使用的兩個字母的國別碼"""
for country_code in sorted(COUNTRIES.keys()):
for code, name in COUNTRIES.items():
if name == country_name:
return code
# 如果沒有找到指定的國家呼渣, 就返回None
return None
world_population.py
'''
@File : world_population.py
@Time : 2019/04/06 23:36:41
@Author : leacoder
@Version : 1.0
@Contact : leacock1991@gmail.com
@License :
@Desc : 對json文件格式的數(shù)據(jù)處理,通過pygal繪制世界人口地圖
'''
# here put the import lib
''' 導(dǎo)入畫地圖的模塊 '''
import pygal.maps.world
''' 解析json文件 '''
import json
'''世界地圖的樣式'''
import pygal
from pygal.style import RotateStyle # 十六進制顏色
from pygal.style import LightColorizedStyle # 加亮地圖的顏色
from country_codes import get_country_code
# 將數(shù)據(jù)加載到一個列表中
filename = 'population_data.json'
with open(filename) as f:
pop_data = json.load(f)
# 創(chuàng)建一個包含人口數(shù)量的字典
cc_populations = {}
for pop_dict in pop_data:
if pop_dict['Year'] == '2010':
country_name = pop_dict['Country Name']
# population = int(pop_dict['Value']) # '1127437398.85751' Python不能直接將包含小數(shù)點的字符串'1127437398.85751' 轉(zhuǎn)換為整數(shù)
# 先將字符串轉(zhuǎn)換為浮點數(shù)寞埠, 再將浮點數(shù)轉(zhuǎn)換為整數(shù):
population = int(float(pop_dict['Value']))
code = get_country_code(country_name)
if code:
cc_populations[code] = population
else:
print('ERROR - ' + country_name)
# 根據(jù)人口數(shù)量將所有的國家分成三組
cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
for cc, pop in cc_populations.items():
if pop < 10000000:
cc_pops_1[cc] = pop
elif pop < 1000000000:
cc_pops_2[cc] = pop
else:
cc_pops_3[cc] = pop
# 看看每組分別包含多少個國家
print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))
'''
class pygal.style.RotateStyle(color, step=10, max_=None, base_style=None, **kwargs)
Create a style by rotating the given color
'''
wm_style = RotateStyle('#336699', base_style=LightColorizedStyle) # 十六進制顏色碼
# wm = pygal.Worldmap() # 已不可用 使用.maps.world.World()替代
wm = pygal.maps.world.World() # 初始化一個地圖對象
wm.style = wm_style # 設(shè)置地圖的風格
wm.title = 'World Population in 2010, by Country'
#wm.add('2010', cc_populations)
wm.add('0-10m', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)
wm.render_to_file('world_population.svg')
GitHub鏈接:
https://github.com/lichangke/LeetCode
知乎個人首頁:
https://www.zhihu.com/people/lichangke/
簡書個人首頁:
http://www.reibang.com/u/3e95c7555dc7
個人Blog:
https://lichangke.github.io/
歡迎大家來一起交流學(xué)習