상세 한 설명 은 pyecharts Geo 로 동적 데이터 열력 도 도시 에서 문 제 를 해결 할 수 없습니다.

pyecharts 는 Echarts 도 표를 만 드 는 데 사용 되 는 라 이브 러 리 입 니 다.Echarts 는 바 이 두 오픈 소스 의 데이터 시각 화 JS 라 이브 러 리 입 니 다.주로 데이터 시각 화 에 사용 된다.
본 고 는 주로 pycharts 중의 Geo 로 중국 지 도 를 그 려 서 각 지역 의 1 인당 매출 액 을 나타 낸다.
들 어 오 는 데이터 형 태 는 다음 과 같다.[('상하 이',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)를 동태 적 으로 선택 하고 서로 다른 데이터 차원(1 인당 소비 액,총 소비 액)을 보 여 주 려 면 어떻게 합 니까?
python 의 템 플 릿 엔진 jinja 2 를 소개 합 니 다.이 엔진 은 Django 디자인 을 모방 합 니 다.템 플 릿 은 텍스트 로 문서 의 형식 과 내용 을 분리 하 는 데 사 용 됩 니 다.구체 적 인 소개 와 용법 은 다음 두 링크 를 볼 수 있 습 니 다.
https://www.jb51.net/article/163962.htm
http://docs.jinkan.org/docs/jinja2/templates.html
가장 기본 적 인 방법 은 템 플 릿 을 통 해 템 플 릿 을 만 들 고 렌 더 링 하 는 것 입 니 다.

from jinja2 import Template
 
template = Template('Hello {{string}}!')
template.render(string='world')
일반적인 문자열 변 수 를 제외 하고 jinja 2 는 목록,사전,대상 도 지원 합 니 다.

{{ 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="https://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="https://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>
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기