目录
第十五章 生成数据
数据可视化指的是通过可视化表示来探索数据,它与数据挖掘紧密相关,而数据挖掘指的是使用代码来探索数据集的规律和关联。
数据集可以是用一行代码就能表示的小型数字列表,也可以是数以吉字节的数据。
漂亮的呈现数据关乎的并非仅仅是漂亮的图片,以引人注目的简介方式呈现数据,让观看者能够明白其含义,发现数据集中原本未意识到的规律和意义。
##15.2绘制简单的折线图
import matplotlib.pyplot as plt
squares=[1,4,9,16,25]
plt.plot(squares)
plt.show()== 打开matplot查看器==
###修改标签文字和线条粗细
import matplotlib.pyplot as plt
squares=[1,4,9,16,25]
plt.plot(squares,linewidth=5)
plt.title(‘square numbers’,fontsize=24)== 设置图表标题,并给坐标轴加上标签==
plt.xlabel(‘value’,fontsize=14)
plt.ylabel(‘square of value’,fontsize=14)
plt.tick_params(axis=‘both’,labelsize=14)设置刻度标记大小
plt.show()
###校正图形
当你向plot()提供一系列数字时,它假设第一个数据点对应的x坐标值为0,但我们的第一个点对应的x值为1。为改变这种默认行为,可以给plot同时提供输入值和输出值。
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 numbers’,fontsize=24)
plt.xlabel(‘value’,fontsize=14)
plt.ylabel(‘square of value’,fontsize=14)
plt.tick_params(axis=‘both’,labelsize=14)
plt.show()
###使用scatter()绘制散点图并设置其样式
import matplotlib.pyplot as plt
plt.scatter(2,4,s=200)使用实参s设置绘制图形时使用的点的尺寸
plt.title(‘square numbers’,fontsize=24)
plt.xlabel(‘value’,fontsize=14)
plt.ylabel(‘square of value’,fontsize=14)
plt.tick_params(axis=‘both’,which=‘major’,labelsize=14)
plt.show()
###使用scatter绘制一系列点
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.show()
自动计算数据
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,s=40)
plt.axis([0,1100,0,110000])函数axis()指定了每个坐标轴的取值范围
plt.show()
###删除数据点的轮廓
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,edgecolors=‘none’, s=40)
plt.axis([0,1100,0,110000])
plt.show()
###自定义颜色
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,c=‘red’,edgecolors=‘none’, s=40)改变数据点颜色,可传递参数c
plt.axis([0,1100,0,110000])
plt.show()
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,c=(0,0,0.8),edgecolors=‘none’, s=40)使用RGB颜色模式自定义颜色,将其设置为一个元组,包含三个0~1的小数值,分别表示红色、绿色和蓝色分量
plt.axis([0,1100,0,110000])
plt.show()
###使用颜色映射
颜色映射是一系列颜色,它们从起始颜色渐变到结束颜色。
在可视化中,颜色映射用于突出数据的规律。
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolors=‘none’, s=40)
plt.axis([0,1100,0,110000])
plt.show()
###自动保存图表
import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolors=‘none’, s=40)
plt.axis([0,1100,0,110000])
plt.savefig(‘squares_plot.png’,bbox_inches=‘tight’)
15.3随机漫步
每次行走都完全随机,没有明确的方向,结果是由一系列随机决策决定的。
创建RandomWalk()类
from random import choice
class RandomWalk():
“”“一个生成随机漫步数据的类”""
def __init(self,num_points=5000):
"""初始化随机漫步属性"""
self.num_points=num_points
#所有随机漫步都始于(0,0)
self.x_values=[0]
self.y_values=[0]
选择方向
from random import choice
class RandomWalk():
“”“一个生成随机漫步数据的类”""
def __init(self,num_points=5000):
"""初始化随机漫步属性"""
self.num_points=num_points
#所有随机漫步都始于(0,0)
self.x_values=[0]
self.y_values=[0]
def fill_waik(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)
绘制随机漫步图
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_waik()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
模拟多次随机漫步
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#只要程序处于活跃状态,就不断模拟随机漫步
while True:
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_waik()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
keep_running=input("make another walk?(y/n): ")
if keep_running=='n':
break
设置随机漫步图的样式
定制图表,以突出每次漫步的特征,并让分散注意力的元素不那么显眼。
给点着色
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#只要程序处于活跃状态,就不断模拟随机漫步
while True:
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_waik()
points_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=points_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15)
plt.show()
keep_running=input("make another walk?(y/n): ")
if keep_running=='n':
break
重新绘制起点和终点
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#只要程序处于活跃状态,就不断模拟随机漫步
while True:
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_waik()
points_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=points_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15)
#突出起点和终点
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)
plt.show()
keep_running=input("make another walk?(y/n): ")
if keep_running=='n':
break
隐藏坐标轴
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#只要程序处于活跃状态,就不断模拟随机漫步
while True:
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_waik()
points_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=points_numbers, cmap=plt.cm.Blues, edgecolors='none', s=15)
# 突出起点和终点
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)
# 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
keep_running = input("make another walk?(y/n): ")
if keep_running == 'n':
break
增加点数
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#只要程序处于活跃状态,就不断模拟随机漫步
while True:
#创建一个RandomWalk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_waik()
#绘制点并将图形显示出来
points_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=points_numbers,cmap=plt.cm.Blues,edgecolors='none',s=1)
#突出起点和终点
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)
#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
keep_running=input("make another walk?(y/n): ")
if keep_running=='n':
break
调整尺寸以适合屏幕
import matplotlib.pyplot as plt
from randam_walk import RandomWalk
#只要程序处于活跃状态,就不断模拟随机漫步
while True:
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_waik()
# 设置绘图窗口尺寸
plt.figure(figsize=(10, 6))
# 绘制点并将图形显示出来
points_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=points_numbers, cmap=plt.cm.Blues, edgecolors='none', s=1)
# 突出起点和终点
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)
# 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
keep_running = input("make another walk?(y/n): ")
if keep_running == 'n':
break
15.4使用pygal模拟掷骰子
创建Die类
from random import randint
class Die():
“”“表示一个骰子的类”""
def __init__(self,num_sides=6): ==方法 __init__()接受一个可选参数==
"""骰子默认6面"""
self.num_sides=num_sides
def roll(self):
"""返回一个位于1和骰子面熟之间的随机值"""
return randint(1,self.num_sides)
== 方法roll()使用函数randint()来返回一个1和面数之间的随机数==
掷骰子
from die import Die
#创建一个D6
die = Die()
#掷几次骰子,并将结果存储在一个列表中
results=[]
for roll_num in range(100):
result=die.roll()
results.append(result)
print(results)
分析结果
from die import Die
#创建一个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)
print(frequencies)
绘制直方图
import pygal
from die import Die
#创建一个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=“results 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’)
同时掷两个骰子
import pygal
from die import Die
#创建两个D6骰子
die_1=Die()
die_2=Die()
#掷骰子多次,并将结果存储在一个列表中
results=[]
for roll_num in range(1000):
result=die_1.roll()+die_2.roll()
results.append(result)
#分析结果
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)
#可视化结果
hist=pygal.Bar()
hist.title=“results of rolling two D6 1000 times.”
hist.x_labels=[‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’,‘10’,‘11’,‘12’]
hist.x_title=“result”
hist.y_title=“frequency of result”
hist.add(‘D6+D6’,frequencies)
hist.render_to_file(‘die_visual_2.svg’)
同时掷两个面数不同的骰子
from die import Die
import pygal
#创建一个D6和一个D10
die_1=Die()
die_2=Die(10)
#掷骰子多次,并将结果存储在一个列表中
results=[]
for roll_num in range(50000):
result=die_1.roll()+die_2.roll()
results.append(result)
#分析结果
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)
#可视化结果
hist=pygal.Bar()
hist.title=“results of rolling D6 and D10 50000 times.”
hist.x_labels=[‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’,‘10’,‘11’,‘12’,‘13’,‘14’,‘15’,‘16’]
hist.x_title=“result”
hist.y_title=“frequency of result”
hist.add(‘D6+D10’,frequencies)
hist.render_to_file(‘die_visual_3.svg’)
第十六章 下载数据
16.1CSV文件格式
要在文本文件中存储数据,最简单的方式是将数据作为一系列以逗号分隔的值(CSV)写入文件。
分析CSV文件头
CSV模块包含在Python标准库中,可用于分析从深V文件中的数据行,让我们能够快速提取感兴趣的值。
import csv
filename=‘data/sitka_weather_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
print(header_row)
打印文件头及位置
import csv
filename=‘data/sitka_weather_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
== 对列表调用了enumerate来获取每个元素的索引及其值==
for index,column_header in enumerate(header_row):
print(index,column_header)
提取并读取数据文件
import csv
#从文件中获取最高气温
filename=‘data/sitka_weather_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
highs=[]
for row in reader:
highs.append(row[1])
print(highs)
绘制气温图表
import csv
from matplotlib import pyplot as plt
#从文件中获取最高气温
filename=‘data/sitka_weather_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
highs=[]
for row in reader:
highs.append(row[1])
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(highs,c=‘red’)
#设置图形格式
plt.title(‘daily high temperatures, july 2014’, fontsize=24)
plt.xlabel(’’,fontsize=16)
plt.ylabel(‘tamperature(F)’,fontsize=16)
plt.tick_params(axis=‘both’,which=‘major’,labelsize=16)
plt.show()
模块datetime
from datetime import datetime
first_date=datetime.strptime(‘2014-7-1’,’%Y-%m-%d’)
print(first_date)
在图表中添加日期
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高气温
filename=‘data/sitka_weather_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
dates,highs=[]
for row in reader:
current_date=datetime.strptime(row[0],'%Y-%m-%d')
dates.append(current_date)
high=int(row[1])
highs.append(high)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c=‘red’)
#设置图形格式
plt.title(‘daily high temperatures, july 2014’, fontsize=24)
plt.xlabel(’’,fontsize=16)
fig.autofmt_xdate()
plt.ylabel(‘tamperature(F)’,fontsize=16)
plt.tick_params(axis=‘both’,which=‘major’,labelsize=16)
plt.show()
再绘制一个数据系列
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取日期、最低气温、最高气温
filename=‘data/sitka_weather_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
dates,highs,lows=[],[],[]
for row in reader:
current_date=datetime.strptime(row[0],'%Y-%m-%d')
dates.append(current_date)
high=int(row[1])
highs.append(high)
low = int(row[3])
lows.append(low)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c=‘red’)
plt.plot(dates,lows,c=‘blue’)
#设置图形格式
plt.title(‘daily high temperatures, july 2014’, fontsize=24)
plt.xlabel(’’,fontsize=16)
fig.autofmt_xdate()
plt.ylabel(‘tamperature(F)’,fontsize=16)
plt.tick_params(axis=‘both’,which=‘major’,labelsize=16)
plt.show()
错误检查== ==
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取日期、最低气温、最高气温
filename=‘data/death_valley_2018_simple.csv’
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
dates,highs,lows=[],[],[]
for row in reader:
current_date=datetime.strptime(row[0],'%Y-%m-%d')
dates.append(current_date)
high=int(row[1])
highs.append(high)
low = int(row[3])
lows.append(low)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c=‘red’)
plt.plot(dates,lows,c=‘blue’)
#设置图形格式
plt.title(‘daily high temperatures, july 2014’, fontsize=24)
plt.xlabel(’’,fontsize=16)
fig.autofmt_xdate()
plt.ylabel(‘tamperature(F)’,fontsize=16)
plt.tick_params(axis=‘both’,which=‘major’,labelsize=16)
plt.show()
16.2制作世界人口地图:JSON格式
第十七章使用API
编写一个独立的程序,并对其获取的数据进行可视化,这个程序将使用Web应用编程接口(API)自动请求网站特定信息而不是整个网页,再对这些信息进行可视化。
17.1 使用Web API
Web API是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互,这种请求称为API调用。
请求的数据以易于处理的格式(如JSON或CSV)返回。
依赖于外部数据源的大多数应用程序都依赖于API调用,如集成社交媒体网站的应用程序。
Git和GitHub
使用API调用请求数据
安装requiests
处理API响应
import requests
#执行PAI调用并存储响应
url=‘https://api.github.com/search/repositories?q=language:python&sort=stars’
r=requests.get(url)
print(“status code:”,r.status_code)
#将API响应存储在一个变量中
response_dict=r.json()
#处理结果
print(response_dict.keys())
处理响应字典
import requests
#执行PAI调用并存储响应
url=‘https://api.github.com/search/repositories?q=language:python&sort=stars’
r=requests.get(url)
print(“status code:”,r.status_code)
#将API响应存储在一个变量中
response_dict=r.json()
print(“tatal repositories:” , response_dict[‘total_count’])
#探索有关仓库的信息
repo_dicts=response_dict[‘items’]
print(“repositories returned:”, len(repo_dicts))
#研究第一个仓库
repo_dict=repo_dicts[0]
print("\nkeys:",len(repo_dict))
for key in sorted(repo_dict.keys()):
print(key)
17.2使用pygal可视化仓库
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
#执行PAI调用并存储响应
url=‘https://api.github.com/search/repositories?q=language:python&sort=stars’
r=requests.get(url)
print(“status code:”,r.status_code)
#将API响应存储在一个变量中
response_dict=r.json()
print(“tatal repositories:” , response_dict[‘total_count’])
#研究有关仓库的信息
repo_dicts=response_dict[‘items’]
names,stars=[],[]
for repo_dict in repo_dicts:
names.append(repo_dict[‘name’])
stars.append(repo_dict[‘stargazers_count’])
#可视化
my_style=LS(’#333366’,base_style=LCS)
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title=‘most_starred python projects on github’
chart.x_labels=names
chart.add(’’,stars)
chart.render_to_file(‘python_repos.svg’)
改进pygal图表
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
#执行PAI调用并存储响应
url=‘https://api.github.com/search/repositories?q=language:python&sort=stars’
r=requests.get(url)
print(“status code:”,r.status_code)
#将API响应存储在一个变量中
response_dict=r.json()
print(“tatal repositories:” , response_dict[‘total_count’])
#研究有关仓库的信息
repo_dicts=response_dict[‘items’]
names,stars=[],[]
for repo_dict in repo_dicts:
names.append(repo_dict[‘name’])
stars.append(repo_dict[‘stargazers_count’])
#可视化
my_style=LS(’#333366’,base_style=LCS)
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
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title=‘most_starred python projects on github’
chart.x_labels=names
chart.add(’’,stars)
chart.render_to_file(‘python_repos_1.svg’)
添加自定义工具提示
在pygal中,将鼠标指向条形将显示它表示的信息,称为工具提示。
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
my_style=LS(’#333366’,base_style=LCS)
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title=‘python projects’
chart.x_labels=[‘httpie’,‘django’,‘flask’]
plot_dicts=[
{‘value’:16101,‘label’:‘description of httpie.’},
{‘value’:15028,‘label’:‘description of django.’},
{‘value’:14798,‘label’:‘description of flask.’}
]
chart.add(’’,plot_dicts)
chart.render_to_file(‘bar_descriptions.svg’)
根据数据绘图
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
#执行PAI调用并存储响应
url=‘https://api.github.com/search/repositories?q=language:python&sort=stars’
r=requests.get(url)
print(“status code:”,r.status_code)
#将API响应存储在一个变量中
response_dict=r.json()
print(“tatal repositories:” , response_dict[‘total_count’])
#研究有关仓库的信息
repo_dicts=response_dict[‘items’]
print(‘number of items:’,len(repo_dicts))
names,plot_dicts=[],[]
for repo_dict in repo_dicts:
names.append(repo_dict[‘name’])
plot_dict={
'value':repo_dict['stargazers_count'],
'label':repo_dict['description'],
}
plot_dicts.append(plot_dict)
#可视化
my_style=LS(’#333366’,base_style=LCS)
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
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title=‘most_starred python projects on github’
chart.x_labels=names
chart.add(’’,plot_dicts)
chart.render_to_file(‘python_repos_2.svg’)
在图表中添加可单击的链接
pygal允许将图表中的每个条形用作网站的链接
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
#执行PAI调用并存储响应
url=‘https://api.github.com/search/repositories?q=language:python&sort=stars’
r=requests.get(url)
print(“status code:”,r.status_code)
#将API响应存储在一个变量中
response_dict=r.json()
print(“tatal repositories:” , response_dict[‘total_count’])
#研究有关仓库的信息
repo_dicts=response_dict[‘items’]
print(‘number of items:’,len(repo_dicts))
names,plot_dicts=[],[]
for repo_dict in repo_dicts:
names.append(repo_dict[‘name’])
plot_dict={
'value':repo_dict['stargazers_count'],
'label':repo_dict['description'],
'xlink':repo_dict['html_url'],
} == pygal根据与键‘XLink’相关联的URL将每个条形都转换为活跃的链接==
plot_dicts.append(plot_dict)
#可视化
my_style=LS(’#333366’,base_style=LCS)
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
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title=‘most_starred python projects on github’
chart.x_labels=names
chart.add(’’,plot_dicts)
chart.render_to_file(‘python_repos_3.svg’)
第十八章 Django入门
Django是一个web框架——一套用于开发交互式网站的工具‘它能够响应网页的请求,还能让你更轻松的读写数据库、管理用户等。
18.1 建立项目
建立项目时,首先需要以规范的方式对项目进行描述,再建立虚拟环境,以便在其中创建项目。
制定规范
完整的规范详细说明了项目的目标,阐述了项目的功能,并讨论了项目的外观和用户界面。
建立虚拟环境
虚拟环境是系统的一个位置,可以在其中安装包,并将其与其他Python包隔离。