[Python Data Visualization Basics] matplotlib, pygal library, CSV module, json, map of world population, API

pyplot module of matplotlib library

1. Draw a line chart

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 plot

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 library

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

CSV module

 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 () # Automatically adjust the X-axis label to avoid overlapping
data processing methods
1. Use try-except exception handling
2. Use continue
3. remove ()
4.del

Json module

json.dump (number, f_obj) #Two actual parameters: data to be stored nmber, file object f_obj
json.load (f_obj) #Load information in .json file

Map the world population

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

Use API (requests package)

API web application interface, used for program interaction requesting specific information using the URL of Juyi
request Python to interact with the website

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)


Published 4 original articles · received 1 · views 128

Guess you like

Origin blog.csdn.net/qq_34385466/article/details/104371401