您的位置:首页 > Web前端 > JavaScript

[Python数据可视化基础]matplotlib、pygal库、CSV模块、json、绘制世界人口地图、API

2020-03-08 15:20 676 查看

matplotlib库之 pyplot模块

1.绘制折线图

plot(x,y)#x,y可为表达式
xlabel("title_name",fontsize=14)#设置x,y标签
tick_params(“both”,labelsize=14)#设置both of x y 刻度
axis([x_min,x_max,y_min,y_max])#设置坐标轴范围
fill_between(x,y1,y2,facecolor='bule',alpha=0.1)#填充两线

2.散点图

scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolor='none',s=40,alpha=0.5)#cm方法可设置颜色映射;edgcolor为轮廓颜色;c为散点颜色;alpha为透明度
savefig('fil_name.png',bbox_inches='tight') #自动保存生成图并截去空白
axes().get_xaxis().set_visible(Fasle) #隐藏坐标轴
figure(figsize=(10,6)) #绘图窗口大小

pygal库

bar=Bar()#Bar类,创建条形图实例
bar.x_label=[] #设置图像参数
bar.add(' 标签 ',frequencies) #frequencies为输入值
bar.renger_to_file('  .svg') #结果保存为svg格式

CSV模块

import csv
with open(filename) as f:
reader=csv.reader(f)#创建阅读器对象
header_row=next(reader)#返回文件下一行,初次调用结果即为表头
dates,highs=[],[]
for row in reader:
high=int(row[1])
date=datetime.strptime(row[0],"%Y-%m-%d")#将CVS中时间行读取
dates.append(date)
highs.append(high)

autofmt_xdate()#自动调整X轴标签,避免重叠
处理数据缺失的方法
1.使用try-except异常处理
2.使用continue
3.remove()
4.del

Json模块

json.dump(number,f_obj) #两个实参:要存储的数据nmber,文件对象f_obj
json.load(f_obj) #加载.json文件中的信息

绘制世界人口地图

world_populations.py

import pygal
import pygal.maps.world
from country_codes import get_country_code
from pygal.style import  RotateStyle

filename='population_data.json'
with open(filename) as f:
pop_data=json.load(f)
cc_populations={}#创建包含人口数量的字典
for pop_dict in pop_data:
if pop_dict['Year']=='2010':
cuntry_name=pop_dict['Country Name']
population=int(float(pop_dict['Value']))
code=get_country_code(cuntry_name)
if code:
cc_populations[code]=population

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
wm=pygal.maps.world.World()#创建Worldmap实例
wm_style=RotateStyle('#336699')
wm=pygal.maps.world.World(style=wm_style)#pygal.Worldmap()不存在
wm.title='World Popolations in 2010'
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')

country_code.py
from pygal.maps.world import COUNTRIES  #pygal.i18n已不存在,查找国别码
def get_country_code(country_name):
'''根据指定国家,返回国别码'''
for code,name in COUNTRIES.items():#COUNTRIES 国家名-国别码对
if name==country_name:
return code
return  None

使用API(requests包)

API web应用接口,用于使用聚义的URL请求特定信息的程序交互
requestPython与网站进行交互

import requests
import pygal
# Make an API call, and store the response.
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)#将响应对象存储在变量r
print("Status code:", r.status_code)status_code核实请求是否成功

# 将API响应值.json格式换为Python字典形式
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])

# 探索有关仓库信息
repo_dicts = response_dict['items']#items值是包含很多字典的列表,每个字典内容为仓库信息

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'],
}
plot_dicts.append(plot_dict)
  • 点赞
  • 收藏
  • 分享
  • 文章举报
灰灰呀嘿 发布了3 篇原创文章 · 获赞 1 · 访问量 77 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: