要了解使用Pygal可创建什么样的图表,请查看图表类型画廊:访问http://www.pygal.org/
1、实例
模拟筛子
die.py文件:
from random import randint
class Die():
def __init__(self,num_sides=6):
self.num_sides=num_sides
def roll(self):
return randint(1,self.num_sides);
main.py文件:
from die import Die
import pygal
die = Die()
results = []
for roll_num in range(10):
result = die.roll()
results.append(result)
print(results)
# 分析结果
freqs = []
for value in range(1, die.num_sides + 1):
freq = results.count(value)
freqs.append(freq)
print(freqs)
# 对结果可视化
hist = pygal.Bar()
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist._title = "resss";
hist.add('D6', freqs)
hist.render_to_file('ddd.svg')
结果:
柱状图
2、读取JSON格式
新建json文件:
[ {
"Country Name": "Arab World",
"Country Code": "ARB",
"Year": "1960",
"Value": "96388069"
},
{
"Country Name": "Arab World",
"Country Code": "ARB",
"Year": "1961",
"Value": "98882541.4"},
]
hello.py源文件:
import json fileName = 'json.json' with open(fileName) as f: opo_data = json.load(f) for opo_item in opo_data: if opo_item['Year'] == '1960': countryName = opo_item['Country Name'] population = opo_item['Value'] print('city:' + countryName + ':' + population)
Pygal使用的国别码存储在模块i18n (internationalization的缩写)中。