下载CSV格式数据,进行可视化
csv.reader()创建一个与文件有关联的阅读器(reader)对象,reader处理文件中的第一行数据,并将每一项数据都存储在列表中
head_row = next(reader) 返回文件的下一行,CSV文件第一行为头文件
datetime.strptime(row[0], '%Y-%m-%d-%H-%M-%S') 将字符串'2018-2-15-13-35-1'转换为一个表示日期时间的对象
plt.text() 给图表添加注释,其中%.nf其中n表示显示小数后面几位,%b表示只标注y
plt.annotate() 参数xytext表示偏移距离,%b表示只标注y
fill_between()接受一个x值系列和两个Y值系列,并填充两个y值系列之间的空间,参数alpha值代表颜色透明度,默认1
参数facecolor代表填充颜色
from datetime import datetime
import matplotlib.pyplot as plt
import csv
import numpy as np
with open('csv_file\photo.csv') as f_obj:
reader = csv.reader(f_obj)
dates,heights_1,heights_2 = [],[],[]
for row in reader:
try:
height_1 = float(row[3])#将字符串转换为浮点型
height_2 = float(row[4])
# 将字符串'2018-2-15-13-35-1'转换为一个表示日期时间的对象
date = datetime.strptime(row[0], '%Y-%m-%d-%H-%M-%S')
except ValueError: #如果有哪一天的数据缺失,打印缺失日期
print(date,'missing data.')
else:
# 将所有高程插入列表
dates.append(date)
heights_1.append(height_1)
heights_2.append(height_2)
fig = plt.figure(figsize=(12,8))
plt.tick_params(axis='both',labelsize=14)
#为防止x轴标签重叠,让日期型的x轴标签自动展现
fig.autofmt_xdate(rotation=45)
#在同一个窗口中绘制两条折线
x = np.array(dates)
y = np.array(heights_1)
for a,b in zip(x,y):
#用text()标注,%.nf其中n表示显示小数后面几位,%b表示只标注y
plt.text(a,b+0.1,'%.2f'%b,ha = 'center',va = 'bottom',
fontsize=8)
#用annotate()标注,xytext表示偏移距离,%b表示只标注y
#plt.annotate('%s'%b,xy=(a,b),xytext=(-20,10),
#textcoords='offset points',fontsize=8)
plt.plot(dates,heights_1,linewidth=3,c='c')
x = np.array(dates)
y = np.array(heights_2)
for a,b in zip(x,y):
plt.text(a, b + 0.1, '%.2f' % b, ha='center', va='bottom',
fontsize=8)
plt.plot(dates,heights_2,linewidth=3,c='red')
#fill_between()接受一个x值系列和两个Y值系列,并填充两个y值系列之间的空间
plt.fill_between(dates,heights_1,heights_2,facecolor='greenyellow',
alpha=0.3)#alpha值代表颜色透明度,默认1
plt.show()
下载JSON格式文件可视化
import json --读取,写入json文件
from pygal.style import RotateStyle,LightColorizedStyle,LightenStyle --定义地图样式
import pygal_maps_world.maps (import pygal.maps.world也可以)
from pygal_maps_world.i18n import COUNTRIES -- 获取两位国别码和国家名
wm=pygal_maps_world.maps.World() --定义一个世界地图实例
南北美洲所有国家的国别码:
wm.add('North America',['ca','mx','us'])
wm.add('Central America',['bz','cr','gt','hn','ni','pa','sv'])
wm.add('South America',['ar','bo','br','cl','co','ec','gf',
'gy','pe','py','sr','uy','ve'])
Pygal样式保存在模块style中:
RotateStyle:修改风格(通过调整指定颜色创建样式)
LightenStyle:轻盈风格(通过赋予特定的色彩来营造风格)
DarkenStyle:黑暗风格(通过使给定颜色变暗创建样式)
SaturateStyle:饱和风格(通过饱和给定颜色创建样式)
DesaturateStyle:去饱和风格(通过淡化给定颜色创建样式)
LightColorizedStyle:加亮颜色(通过加亮给定颜色创建样式)
RotateStyle('#336699')给三个分组调整颜色,十六进制的RGB颜色是一个以#开头的
字符串,后面6个字符分别表示红绿蓝三个颜色占的分量;hex color chooser-十六进制
颜色选择器;LightColorizedStyle 此类可单独使用,加亮地图颜色(包括整个图表的主题)
同时也可以放在RotateStyl()函数中传给实参base_style
import json
from pygal.style import RotateStyle,LightColorizedStyle
#import pygal.maps.world
import pygal_maps_world.maps
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
filename = 'json_file\population_data.json'
with open(filename) as f:
#将文件中的字典存储到列表中
pop_data = json.load(f)
#将每个国家2010年的人口数据加入字典
cc_populations = {}
for pop_dict in pop_data:
if pop_dict['Year'] == '2010':
country_name = pop_dict["Country Name"]
population = int(float(pop_dict['Value']))
code = get_country_code(country_name)
if code:
cc_populations[code] = population
#print(code + ':' + str(population))
else:
print( 'Error - ' + country_name)
#将世界人口数量等级分为三组
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_populations),len(cc_pops_1),len(cc_pops_2),len(cc_pops_3))
wm_style = RotateStyle('#336699',base_style=LightColorizedStyle)
#wm = pygal.maps.world.World()
wm = pygal_maps_world.maps.World(style=wm_style)
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('images\world_population.svg')