亲宝软件园·资讯

展开

详解用pyecharts Geo实现动态数据热力图城市找不到问题解决

人气:0

pyecharts 是一个用于生成 Echarts 图表的类库。 Echarts 是百度开源的一个数据可视化 JS 库。主要用于数据可视化。

本文主要是用pycharts中的Geo绘制中国地图,在图中显示出各个地区的人均销售额

传入的数据形如:[('上海',30), ('北京',50), ... ...]


li=[]
for i,row in filtered.iterrows():
 li.append((row['city'],int(row['per_capita'])))
 
geo = Geo("sales per capita", "city", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59')
attr, value = geo.cast(li)
geo.add("", attr, value, visual_range=[187, 820], visual_text_color="#fff", symbol_size=15, is_visualmap=True)
geo.show_config()
geo.render()
 
geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center", width=1200, height=600,
   background_color='#404a59')
attr, value = geo.cast(li)
geo.add("", attr, value, type="heatmap", is_visualmap=True, visual_range=[200, 300], visual_text_color='#fff')
geo.show_config()
geo.render()
 
geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center",
   width=1200, height=600, background_color='#404a59')
attr, value = geo.cast(li)
geo.add("", attr, value, type="effectScatter", is_random=True, effect_scale=5)
geo.show_config()
geo.render()

原来的包的问题是,经纬度非常不全,一旦有找不到的,就画不出来,方案一是把找不到的数据删掉再画

另一种办法是到百度地图api里把找不到的地方的经纬度加进原始的包里

搜索:百度地图api-》地图api示例-》地址解析


复制这些经纬度;

打开pyecharts包里的base.py,找到记录经纬度信息的地方,把刚才的经纬度信息补上去


如此便可以把所有数据都呈现在地图上了

如果我想动态选择年份(2013-2017)以及选择展现不同数据维度(人均消费额,总消费额)怎么办?

这里要介绍一个python的模板引擎jinja2,该引擎仿照Django设计。模板是文本,用于分离文档的形式和内容,具体的介绍和用法可以看下面两个链接

https:

http://docs.jinkan.org/docs/jinja2/templates.html

最基本的方法是通过Template创建模板并且渲染

from jinja2 import Template
 
template = Template('Hello {{string}}!')
template.render(string='world')

除了普通的字符串变量,jinja2还支持列表,字典和对象,

{{ mydict['key'] }}
{{ mylist[3] }}
{{ mylist[myintvar] }}
{{ myobj.somemethod() }}
{{myobj.someattribute}}

于是我们可以通过创建一个字典,将不同年份不同维度的数据都放入字典中,在展示数据时,将指定数据传入模板

options={}

 for year in range(2013, 2018):
  options[year] = {}
  filtered = grouped[grouped['year'] == year]
  for dim in ('sales', 'per_capita'):
   li = []
   for i, row in filtered.iterrows():
    li.append((row['city'], int(row[dim])))
   if dim == 'per_capita':
    geo = Geo(dim, "city (单位:元/人)", title_color="#fff", title_pos="center", width=1200, height=600,
       background_color='#404a59')
    attr, value = geo.cast(li)
    geo.add("", attr, value, visual_range=[380, 450], visual_text_color="#fff", symbol_size=15, is_visualmap=True)
   else:
    geo = Geo(dim, "city (单位:百万)", title_color="#fff", title_pos="center", width=1200, height=600,
       background_color='#404a59')
    attr, value = geo.cast(li)
    geo.add("", attr, value, visual_range=[10, 100], visual_text_color="#fff", symbol_size=15, is_visualmap=True)
   options[year][dim] = geo._option
 with open("template.html", encoding='utf-8') as f:
  template = jinja2.Template(f.read())
 html = template.render(data=json.dumps(options))
 with open("city_chart.html", "w") as f:
  f.write(html)

通过查看base.py里的render()可以看到传入模板的是self._option

 def render(self, path="render.html"):
  """ 渲染数据项,生成 html 文件
  :param path:
   生成 html 文件保存路径
  """
  from pyecharts import temple as Tp
  temple = Tp._temple
  series = self._option.get("series")
  for s in series:
   if s.get('type') == "wordCloud":
    temple = Tp._temple_wd
    break
   if s.get('type') == "liquidFill":
    temple = Tp._temple_lq
    break
  my_option = json.dumps(self._option, indent=4, ensure_ascii=False)
  __op = temple\
   .replace("myOption", my_option)\
   .replace("myWidth", str(self._width))\
   .replace("myHeight", str(self._height))
  try:  # for Python3
   with open(path, "w+", encoding="utf-8") as fout:
    fout.write(__op)
  except:  # for Python2
   with open(path, "w+") as fout:
    fout.write(__op)

template亦可仿照temple.py

<html>
 
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="external nofollow" type="text/css">
 <link rel="stylesheet" href="http://pingendo.github.io/templates/blank/theme.css" rel="external nofollow" type="text/css">
 <link href="https://cdn.bootcss.com/bootstrap-select/2.0.0-beta1/css/bootstrap-select.css" rel="external nofollow" rel="stylesheet">
 <script src="https://cdn.bootcss.com/bootstrap-select/2.0.0-beta1/js/bootstrap-select.js"></script>
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
 <script src="http://pingendo.com/assets/bootstrap/bootstrap-4.0.0-alpha.6.min.js"></script>
 <script src="http://oog4yfyu0.bkt.clouddn.com/echarts.min.js"></script>
 <script type="text/javascript " src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/china.js"></script>
 <script type="text/javascript " src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/world.js"></script>
 <script type="text/javascript " src="http://oog4yfyu0.bkt.clouddn.com/wordcloud.js"></script>
 ... ...
 </head>
 
<body>
 <div class="py-5">
 <div class="container">
  <div class="row">
  <div class="col-md-4">
   <select class="selectpicker" id="year">
    <option>2013</option>
    <option>2014</option>
    <option>2015</option>
    <option>2016</option>
    <option>2017</option>
   </select>
  </div>
  <div class="col-md-4">
   <select class="selectpicker" id="dim">
   <option value="sales">total_sales</option>
   <option value="per_capita">sales per capita</option>
   <option value="count">count</option>
   </select>
  </div>
  <div class="col-md-4">
   <select class="selectpicker" id="customer_type">
   <option value="new_customer">new_customer</option>
   <option value="old_customer">old_customer</option>
   <option value="members">members</option>
   </select>
  </div>
  <div class="col-md-4">
   <a class="btn btn-default" href="#" rel="external nofollow" onclick="show()">refresh</a>
  </div>
  </div>
  <div class="row"> 
  <div class='col-md-12'>
    <div id="main" style="width: 1200px;height:600px;"></div>
  </div>
  </div>
 
 </div>
 </div>
<script type="text/javascript">
var data={{data}};
function show(){
 var year=$("#year").val();
 var dim=$("#dim").val();
 var customer_type=$("#customer_type").val();
 var myChart = echarts.init(document.getElementById('main'));
 var option=data[year][dim][customer_type];
 option['tooltip']={'formatter':function(params){return params['name']+':'+params['value'][2]}};
 myChart.setOption(option);
} 
$(show);//加载完文档之后运行这个函数
</script>
</body>
 
</html>
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论