#16-2 比较锡特卡和死亡谷的气温 :在有关锡特卡和死亡谷的图表中,气温刻度反映了数据范围的不同。为准确地比较锡特卡和死亡谷的气温范围,
# 需要在y 轴上使用相同的刻度。为此,请修改图16-5和图16-6所示图表的y 轴设置,对锡特卡和死亡谷的气温范围进行直接比较
# (你也可以对任何两个地方的气温范围进行比较)。你还可以尝试在一个图表中呈现这两个数据集。
import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename = 'death_valley_2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
try:
current_date = datetime.strptime(row[0],"%Y-%m-%d")
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)
fig = plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)
plt.plot(dates,lows,c='blue',alpha=0.5)
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)
plt.title("Daily high and low temperatures - 2014\nDeath Valley, CA",fontsize=24)
plt.xlabel("",fontsize=16)
fig.autofmt_xdate()
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
16-2结果:
#16-3 降雨量 :选择你感兴趣的任何地方,通过可视化将其降雨量呈现出来。为此,可先只涵盖一个月的数据,
# 确定代码正确无误后,再使用一整年的数据来运行它。
import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename = 'sitka_weather_2014.csv'
with open(filename) as f:
reader = csv.reader(f)
line = next(reader)
clouds,dates = [],[]
for row in reader:
try:
current_date = datetime.strptime(row[0],"%Y-%m-%d")
cloud = row[-3]
except ValueError:
print(row[0],'missing data')
else:
clouds.append(cloud)
dates.append(current_date)
fig = plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,clouds,c='red',alpha=0.1)
plt.title("Daily CloudCover -2014\nSitKa",fontsize=24)
plt.xlabel("Time",fontsize=16)
plt.ylabel("CloudCover",fontsize=16)
fig.autofmt_xdate()
plt.show()
16-3结果:
16-5人口分布地图:
import pygal
import json
from pygal_maps_world.i18n import COUNTRIES
def get_country_code(country_name):
for code,name in COUNTRIES.items():
if name == country_name:
return code
return None
cc_populations = {}
filename = 'population_data.json'
with open(filename) as f:
pop_data = json.load(f)
for pop_dict in pop_data:
if pop_dict['Year'] == '2010':
country = pop_dict['Country Name']
#人口数换为浮点型,再转换为int型统一格式,供pygal绘图使用,需特别注意,否则会报错
population = int(float(pop_dict['Value']))
code = get_country_code(country)
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()
wm.title = "World Population in 2010,by Country"
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')
结果(world_population.svg文件):
#17---使用API
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
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("Total 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'],
}
plot_dicts.append(plot_dict)
#可视化
my_style = LS('#333366',base_style=LCS)
chart = pygal.Bar(style=my_style,x_label_rotation=45)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('',plot_dicts)
chart.render_to_file('python_repos.svg')
17结果: