def creat_lan_charts(data_list): page = Page() style = Style(title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') chart = Geo("python", "python-city", **style.init_style) attr, value = chart.cast(data_list) chart.add("", attr, value, visual_range=[0, 200], visual_text_color="#fff", is_legend_show=False, symbol_size=15, is_visualmap=True, tooltip_formatter='{b}', label_emphasis_textsize=15, label_emphasis_pos='right') page.add(chart) chart = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) attr, value = chart.cast(data_list) chart.add("", attr, value, type="heatmap", is_visualmap=True, visual_range=[0, 200], visual_text_color='#fff', is_legend_show=False) page.add(chart) return page
def geo_test(a, b): attr = pd.Series(unique(a)).values value = pd.Series(b.groupby(a).count()).values data = [("上海", 47647), ("北京", 21454), ("南京", 849), ("南充", 15745), ("南通", 16352), ("合肥", 11895), ("广州", 43589), ("延安", 3180), ("成都", 19979), ("杭州", 33143), ("武汉", 6465), ("沧州", 13223), ("深圳", 31281), ("湖州", 22433), ("牡丹江", 20526), ("西安", 30548), ("金华", 22799), ("阜阳", 12004)] geo = Geo("全国各个城市的门店分布", "数据来源:香飘飘-饿了么爬虫原始数据", title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59") attr_x, value_y = geo.cast(data) geo.add("", attr_x, value_y, visual_range=[0, 200], visual_text_color="#fff", symbol_size=15, is_visualmap=True) geo.show_config() geo.render("E:\\py_data_html\\ele_data_2.html") geo
def heat_map(): data = [("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15), ("赤峰", 16), ("青岛", 18), ("乳山", 18), ("金昌", 19), ("泉州", 21), ("莱西", 21), ("日照", 21), ("胶南", 22), ("南通", 23), ("拉萨", 24), ("云浮", 24), ("梅州", 25), ("乌鲁木齐", 40)] geo = Geo("全国主要城市空气质量热力图", "data from pm2.5", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("空气质量热力图", attr, value, visual_range=[0, max(value)], type='heatmap', visual_text_color="#fff", symbol_size=15, is_label_show=True, is_visualmap=True) # geo.show_config() geo.render(path="./data/空气质量热力图.html")
def draw_map(comments): try: attr = comments['cityName'].fillna("zero_token") data = Counter(attr).most_common(100) #data.remove(data[data.index([(i, x) for i, x in (data) if i == 'zero_token'][0])]) geo = Geo("《毒液》观众位置分布", "数据来源:猫眼电影 - SmartCrane采集", title_color="#fff", title_pos="center", width=1000, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 1000], maptype='china', visual_text_color="#fff", symbol_size=10, is_visualmap=True) geo.render("./观众位置分布-地理坐标图.html") # 生成html文件 geo # 直接在notebook中显示 except Exception as e: print(e)
def place2(self): City = [] # 微信好友所在城市 for city in self.friends[1:]: # if city['City']=="东城": # print(city) # return City.append(city['City']) print(City) Citys = collections.Counter(City) # 每个城市对应的数量 values = [] # weixin2 Map for city in set(City): # values 每个城市对应的数量 if (city != '' and city.isalpha()): # 除去没有城市的 和 外国城市 values.append((city, Citys[city])) print(values) geo = Geo(u"%s 各省微信好友分布" % self.nickName, u"冀祥", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') attr, value = geo.cast(values) print(attr, value) geo.add("", attr, value, visual_range=[0, 200], visual_text_color="#fff", symbol_size=15, is_visualmap=True) # geo.show_config() geo.render("%s的好友分部图2.html" % self.nickName)
def render(): # 获取所有城市 cities = [] with open('friends.txt', mode='r', encoding='utf-8') as f: rows = f.readlines() for row in rows: city = row.split(',')[4] if city != '': # 去掉城市名为空的值 cities.append(city) # 对城市数据和坐标文件中的地名进行处理 handle(cities) # 统计每个城市出现的次数 data = Counter(cities).most_common() # 使用Counter类统计出现的次数,并转换为元组列表 print(data) # 根据城市数据生成地理坐标图 geo = Geo('好友位置分布', '', title_color='#fff', title_pos='center', width=800, height=500, background_color='#404a59') attr, value = geo.cast(data) geo.add('', attr, value, visual_range=[0, 500], visual_text_color='#fff', symbol_size=15, is_visualmap=True, is_piecewise=True) geo.render('好友位置分布.html') # 根据城市数据生成柱状图 data_top20 = Counter(cities).most_common(20) # 返回出现次数最多的20条 bar = Bar('好友所在城市TOP20', '', title_pos='center', width=1200, height=600) attr, value = bar.cast(data_top20) bar.add('', attr, value, is_visualmap=True, visual_text_color='#fff', is_more_utils=True, is_label_show=True) bar.render('好友所在城市TOP20.html')
def render(): #获取所在城市 cities = [] with io.open('friends.txt', mode='r', encoding='utf-8') as f: rows = f.readlines() for row in rows: city = row.split(',')[3] if city != '': cities.append(city) handle(cities) data = Counter(cities).most_common() #print(data) #绘执地理坐标图 geo = Geo("好友位置分布", '', title_color='#fff', title_pos='center', width=1200, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add('', attr, value, visual_range=[0, 500], visual_text_color='#fff', symbol_size=15, is_visualmap=True, is_piecewise=True) geo.render('好友位置分布.html')
def test_geo_china_scatter(patched): fixture = "geo_options.json" patched.return_value = "1" cities = [("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15)] geo = Geo("全国主要城市空气质量", "data from pm2.5") attr, value = geo.cast(cities) geo.add( "", attr, value, visual_range=[0, 200], visual_text_color="#fff", is_legend_show=False, symbol_size=15, is_visualmap=True, tooltip_formatter="{b}", label_emphasis_textsize=15, label_emphasis_pos="right", ) actual_options = json.dumps(geo.options, sort_keys=True, indent=4, cls=DefaultJsonEncoder) expected = get_fixture_content(fixture) for a, b in zip(actual_options.split("\n"), expected.split("\n")): eq_(a.strip(), b.strip())
def draw_map(comments): try: attr = comments['cityName'].fillna("zero_token") data = Counter(attr).most_common(300) data.remove(data[data.index([(i, x) for i, x in (data) if i == 'zero_token'][0])]) #print(data) geo = Geo("《Avengers:Endgame》全国观众地域分布", "数据来源:猫眼电影", title_color="#fff", title_pos="center", width=1450, height=725, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 1000], maptype='china', visual_text_color="#fff", symbol_size=10, is_visualmap=True) geo.render("./全国观众地域分布地理坐标图.html") print("全国观众地域分布已完成") except Exception as e: print(e)
def get_map(data): print(data) geo = Geo( "全国必胜客城市分布", "data from pizzahut", title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59", ) try: attr, value = geo.cast(data) geo.add( "", attr, value, visual_range=[0, 200], visual_text_color="#fff", symbol_size=10, is_roam=True, is_visualmap=True, ) geo.render() except ValueError as info: error_city = str(info).split(' ')[-1] print(error_city) dict = {k: v for k, v in data} print((error_city, dict[error_city])) data.remove((error_city, dict[error_city])) get_map(data=data)
def echarts_draw(locations, fileName, path="./", title="地域分布图" , subtitle="location distribute"): """ 生成地域分布的echarts热力图的html文件. :param locations: 样本的省市区, pandas的dataframe类型. :param fileName: 生成的html文件的文件名. :param path: 生成的html文件的路径. :param title: 图表的标题 :param subtitle: 图表的子标题 """ from pyecharts import Geo _base_input_check(locations) map_keys = locations["省"] + "," + locations["市"] + "," + locations["区"] count_map = {} from .infrastructure import SuperMap for map_key in map_keys: if SuperMap.lat_lon_mapper.get(map_key): count_map[map_key] = count_map.get(map_key, 0) + 1 geo = Geo(title, subtitle, title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') _geo_update(geo) attr, value = geo.cast(count_map) geo.add("", attr, value, type="heatmap", is_visualmap=True, visual_text_color='#fff', is_piecewise=True, visual_split_number=10) geo.render(path + fileName)
def test_geo_visualmap_pieces(): data = [ ("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15), ] geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(data) geo.add( "", attr, value, type="effectScatter", is_random=True, is_visualmap=True, is_piecewise=True, visual_text_color="#fff", pieces=[ {"min": 0, "max": 13, "label": "0 < x < 13"}, {"min": 14, "max": 16, "label": "14 < x < 16"}, ], effect_scale=5, ) content = geo._repr_html_() assert '"max": 13' in content assert '"label": "14 < x < 16"' in content
def create_map(data): geo = Geo('《无名之辈》观众位置分布', '数据来源:猫眼采集', title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59") try: attr, value = geo.cast(data) geo.add( "", attr, value, visual_range=[0, 1000], visual_text_color="#fff", symbol_size=15, is_visualmap=True, ) geo.render("观众位置分布-地理坐标图.html") except ValueError as info: error_city = str(info).split(' ')[-1] del data[error_city] create_map(data) data_top10 = Counter(data).most_common(10) print(data_top10) bar = Bar('无名之辈观众来源排行TOP10', '数据来源:猫眼', title_pos='center') attr, value = bar.cast(data_top10) bar.add('', attr, value, is_visualmap=True, visual_range=[0, 3500], visual_text_color='#fff', is_more_utils=True, \ is_label_show=True) bar.render("观众来源排行榜-柱状图.html")
def geo_qgtd(attr_v1: List[Tuple[str, int]], chart_name: str, v1_name: str) -> geo.Geo: """ 生成全国地图-数据通道图 :param attr_v1: 主要数据 :param chart_name: 图表名 :param v1_name: 数据一名 """ style = Style(title_color="#fff", title_pos="center", width=900, height=600, background_color='#404a59') # chart = Map(chart_name, **style.init_style) # chart.add(v1_name, attr, value, maptype='china', is_visualmap=True, # visual_text_color='#000') chart = Geo(chart_name, "", **style.init_style) attr, value = chart.cast(attr_v1) chart.add(v1_name, attr, value, visual_range=[0, 70000], visual_text_color="#fff", is_legend_show=False, symbol_size=15, is_visualmap=True, tooltip_formatter='{b}', label_emphasis_textsize=15, label_emphasis_pos='right', type='effectScatter') return chart
def render_city(cities): # 对城市数据和坐标文件中的地名进行处理 handle(cities) data = Counter(cities).most_common() # 使用Counter类统计出现的次数,并转换为元组列表 print(data) # 定义样式 style = Style(title_color='#fff', title_pos='center', width=1200, height=600, background_color='#404a59') # 根据城市数据生成地理坐标图 geo = Geo('《悲伤逆流成河》粉丝位置分布', **style.init_style) attr, value = geo.cast(data) geo.add('', attr, value, visual_range=[0, 600], visual_text_color='#fff', symbol_size=15, is_visualmap=True, is_piecewise=True, visual_split_number=10) geo.render(d + '/picture/geo.html')
def geographical_location_distribution(): data = pd.read_csv(filepath, encoding='gbk') data['salary'] = data['salary'].apply(lambda xx: re.sub(u'k|K|以上', '', xx)) data['min_salary'] = data['salary'].apply( lambda xx: float(xx.split('-')[0]) * 1000) data['max_salary'] = data['salary'].apply( lambda xx: float(xx.split('-')[1]) * 1000 if len(xx.split('-')) > 1 else float(xx) * 1000) # print data[data['min_salary'] == data['max_salary']] ## xx以上 dataset = [(city, min_salary) for city, min_salary in data['city min_salary'.split()].values] geo = Geo("Python Job Distribution", "", title_pos="center", width=2000, height=1200, background_color='#404a59') attr, value = geo.cast(dataset) geo.add("", attr, value, type="effectScatter", is_visualmap=True, maptype='china', visual_range=[0, 300], effect_scale=5, symbol_size=5, visual_text_color="#fff") geo.render(filedir + 'job_distribution.html')
def test_geo_china_scatter(patched): fixture = "geo_options.json" patched.return_value = "1" cities = [("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15)] geo = Geo("全国主要城市空气质量", "data from pm2.5") attr, value = geo.cast(cities) geo.add( "", attr, value, visual_range=[0, 200], visual_text_color="#fff", is_legend_show=False, symbol_size=15, is_visualmap=True, tooltip_formatter="{b}", label_emphasis_textsize=15, label_emphasis_pos="right", ) actual_options = json.dumps( geo.options, sort_keys=True, indent=4, cls=DefaultJsonEncoder ) expected = get_fixture_content(fixture) for a, b in zip(actual_options.split("\n"), expected.split("\n")): eq_(a.strip(), b.strip())
def plt_place(place, htmlfile): city_name, city_list = clean_cities_name(place) # 对城市名进行清理 city_dict = {city_list[i]: 0 for i in range(len(city_list))} for i in range(len(city_list)): city_dict[city_list[i]] = city_name.count(city_list[i]) print(city_dict) # 根据数量排序 sort_dict = sorted(city_dict.items(), key=lambda d: d[1], reverse=True) city_name = [] city_num = [] for i in range(len(sort_dict)): city_name.append(sort_dict[i][0]) city_num.append(sort_dict[i][1]) data = list(zip(city_name, city_num)) geo = Geo("评论者位置分布", "数据来源知乎", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') attr, value = geo.cast(data) # 注意修改显示范围 geo.add('城市', attr, value, visual_range=[0, 20], visual_text_color='#fff', symbol_size=10, is_visualmap=True, is_picewise=False, visual_split_number=10) geo.render(htmlfile)
def gen_price_map(year=None, month=None, province='china'): # 绘制地区温度图 house_db = HouseDatabase('residential') year_cond = 'year=%d' % year if year is not None else '' month_cond = ' and month=%d' % month if month is not None else '' province_cond = " and province='%s'" % province if province not in [ 'china', '中国' ] else '' condition = year_cond + month_cond + province_cond latest_price = house_db.query_records(condition) cities_prices = [(item['city'], item['price']) for item in latest_price if item['city'] not in STOP_CITY] geo = Geo("", '', title_color="#fff", title_pos="left", background_color='#404a59') # width=1000, height=600, cities, prices = geo.cast(cities_prices) geo.add('%d-%d' % (NOW.year, NOW.month), cities, prices, maptype=province, type="heatmap", is_visualmap=True, visual_range=[numpy.min(prices), numpy.max(prices)], visual_text_color="#fff") geo.render("./out/房价温度图-%s.html" % condition.replace(' and ', '-').replace('=', '_'))
def Cast(self, name, method=None, message=None, max_bin=100): ''' casts data ,and filters data with stopwords :param name: colname :param method: to decide the func returns a dict or tuple(attr,value) :param message: a message the user gives,if not None, will be adding to stopwords :param max_bin: the max number of words on wordcloud :return: ''' string = "".join(self.GetOneCol(name)) brokewords = map( str.strip, open('./config/stopwords/stopwords.txt', "r", encoding="utf-8").readlines()) if message: brokewords = itertools.chain(brokewords, message.split(",")[:]) stopwords = "".join(brokewords) lis = dict( Counter([ tag.strip() for tag in analyse.extract_tags(string, max_bin) if tag.strip() not in stopwords ])) lis = sorted(lis.items(), key=lambda x: x[1], reverse=True) if method is None: return Geo.cast(lis) elif method == "dict": return {k[0]: k[1] for k in lis}
def plot(): for item in all_list(city): data.append((item, all_list(city)[item])) style = Style(title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59") geo = Geo("《邪不压正》粉丝人群地理位置", "数据来源:量子皮皮马", **style.init_style) attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 20], visual_text_color="#fff", symbol_size=20, is_visualmap=True, is_piecewise=True, visual_split_number=4) geo.render("plot.html")
def create_geo_charts(data, title): '''地图''' page = Page() # 样式 style = Style(title_color="#fff", title_pos="center", width=1200, height=600, background_color='#c4ccd3') # 创建地图模型 chart = Geo(title, "", **style.init_style) # 数据 ['上海', '北京', '广州', '深圳', '苏州'] [5, 40, 10, 15, 5] attr, value = chart.cast(data) # 添加数据 chart.add("", attr, value, maptype='china', is_visualmap=True, type="effectScatter", is_legend_show=False, geo_emphasis_color='c4ccd3', visual_text_color='#2f4554') page.add(chart) return page
def getView(self): db = DBUtils() sql = 'select city from comment' city = db.selectallInfo(sql) print(city) for i in city: citys.append(i[0]) data = [] for item in self.all_list(citys): data.append((item, self.all_list(citys)[item])) style = Style(title_color="#fff", title_pos="center", width=950, height=650, background_color="#404a59") geo = Geo("《西红市首富》粉丝人群地理位置", "刘宏伟", **style.init_style) attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[ 0, ], visual_text_color="#fff", symbol_size=20, is_visualmap=True, is_piecewise=True, visual_split_number=5) geo.render('../templates/render.html')
def mapMaking(task_id): client = pymongo.MongoClient("127.0.0.1", 27017) list = [] dict = {} list1 = [] try: db = client.crawlData # 连接test数据库 collection = db.taobao # 访问test数据库中things集合 for m in collection.find({"task_id": task_id}, { "address": 1, "_id": 0 }): if m['address'] in citys: list.append(m['address']) except: pass finally: client.close() # print list # 生成关系,查找键值 for index in list: # 遍历词语列表 if index in dict: dict[index] += 1 # 根据字典键访问键值,如果该键在字典中,则其值+1 else: dict[index] = 1 # 如果键不在字典中,则设置其键值为1 # print dict #{u'\u4e0a\u6d77': 1, u'\u9633\u6c5f': 6, u'\u6210\u90fd': 1, u'\u91d1\u534e': 1} for item in dict.items(): # 化成列表类型 list1.append(item[0]) list1.append(item[1]) # print len(list1) list2 = [] for i in range(0, len(list1), 2): # 拼成pycharts能够输入的格式,步长为2 a = (list1[i], list1[i + 1]) list2.append(a) data = list2 geo = Geo(u"商品在全国售卖主要城市", u"商品", title_color="#fff", title_pos="center", width=1000, height=600, background_color='#404a59') geo.height = 800 geo.width = 1500 attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 60], maptype='china', visual_text_color="#fff", symbol_size=10, is_visualmap=True) geo.render("static/maps/map" + task_id + ".html") # 生成html文件
def draw_city_geo(data): geo = Geo("全国妹子分布城市", "data about beauty", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[10, 2500], visual_text_color="#fff", symbol_size=15, is_visualmap=True) return geo
def keshihua(filepath): #读取城市数据 city = [] with io.open(filepath, mode='r', encoding='utf-8') as f: rows = f.readlines() for row in rows: if len(row.split(',')) == 5: city.append(row.split(',')[2].replace('\n', '')) def all_list(arr): result = {} for i in set(arr): result[i] = arr.count(i) return result data = [] for item in all_list(city): data.append((item, all_list(city)[item])) style = Style(title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59") geo = Geo("《李茶的姑妈》粉丝人群地理位置", "ZGM", **style.init_style) attr, value = geo.cast(data) print("data:", json.dumps(data, ensure_ascii=False)) print("attr:", json.dumps(attr, ensure_ascii=False)) print("value:", value) #添加echarts中没有的地理坐标 geo.add_coordinate(u"射阳", 120.229986, 33.758361) geo.add_coordinate(u"辽中", 122.765409, 41.516826) geo.add_coordinate(u"共青城", 115.808844, 29.248316) geo.add_coordinate(u"邹平", 117.743109, 36.862989) geo.add_coordinate(u"淮阳", 114.886153, 33.731561) geo.add_coordinate(u"万州", 108.380246, 30.807807) geo.add_coordinate(u"牟平", 121.600455, 37.387061) geo.add_coordinate(u"宁国", 118.983171, 30.633882) geo.add_coordinate(u"黔南", 107.523205, 26.264535) geo.add_coordinate(u"泗洪", 33.4761, 118.2236) geo.add_coordinate(u"中牟", 34.7189, 113.9763) geo.add_coordinate(u"黔西南", 25.0879, 104.9064) geo.add_coordinate(u"苍南", 27.5183, 120.4258) geo.add_coordinate(u"浠水", 30.4519, 115.2665) geo.add_coordinate(u"泗洪", 33.4761, 118.2236) geo.add("", attr, value, visual_range=[0, 120], visual_text_color="#fff", symbol_size=20, is_visualmap=True, is_piecewise=True, visual_split_number=4) geo.render("Mrs_fans_geo.html")
def city_viewer(self): dic_city = dict() for friend in self.friends: key = friend["City"] if key not in dic_city.keys(): dic_city[key] = 1 else: dic_city[key] += 1 data = [] max_value = 0 for key, value in dic_city.items(): # 其他地区 if len(key) == 0: continue # 过滤英文等非市级 if len(key) >= 3: continue # 没有找到判断字符串是不是城市的接口,暂时先这样过滤吧 if key == "海淀" or key == "南开" or key == "徐汇": continue data.append(tuple((key, value))) if value > max_value: max_value = value print(key, value) print(data) # city的可视化过程类似province ## 高级可视化 # 安装 pyecharts # pip install pyecharts # 安装 独立的地图包 # pip install echarts-countries-pypkg # pip install echarts-china-provinces-pypkg # pip install echarts-china-cities-pypkg # may need pip install pyecharts_snapshot geo = Geo("微信好友城市分布图", "posted by inspurer", title_color="#000", title_pos="center", width=1000, height=600, background_color='#ffffff') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[1, max_value], visual_range_color=['#d54d2b', '#FF0000'], maptype='china', visual_text_color="#f00", symbol_size=18, is_visualmap=True, geo_normal_color="#22DDDD", geo_emphasis_color="#0033FF") geo.render("view/your_city.html") # 生成html文件 os.startfile(os.getcwd() + "/view/your_city.html")
def demo3(): from pyecharts import Geo data = [("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15), ("赤峰", 16), ("青岛", 18), ("乳山", 18), ("金昌", 19), ("泉州", 21), ("莱西", 21), ("日照", 21), ("胶南", 22), ("南通", 23), ("拉萨", 24), ("云浮", 24), ("梅州", 25), ("文登", 25), ("上海", 25), ("攀枝花", 25), ("威海", 25), ("承德", 25), ("厦门", 26), ("汕尾", 26), ("潮州", 26), ("丹东", 27), ("太仓", 27), ("曲靖", 27), ("烟台", 28), ("福州", 29), ("瓦房店", 30), ("即墨", 30), ("抚顺", 31), ("玉溪", 31), ("张家口", 31), ("阳泉", 31), ("莱州", 32), ("湖州", 32), ("汕头", 32), ("昆山", 33), ("宁波", 33), ("湛江", 33), ("揭阳", 34), ("荣成", 34), ("连云港", 35), ("葫芦岛", 35), ("常熟", 36), ("东莞", 36), ("河源", 36), ("淮安", 36), ("泰州", 36), ("南宁", 37), ("营口", 37), ("惠州", 37), ("江阴", 37), ("蓬莱", 37), ("韶关", 38), ("嘉峪关", 38), ("广州", 38), ("延安", 38), ("太原", 39), ("清远", 39), ("中山", 39), ("昆明", 39), ("寿光", 40), ("盘锦", 40), ("长治", 41), ("深圳", 41), ("珠海", 42), ("宿迁", 43), ("咸阳", 43), ("铜川", 44), ("平度", 44), ("佛山", 44), ("海口", 44), ("江门", 45), ("章丘", 45), ("肇庆", 46), ("大连", 47), ("临汾", 47), ("吴江", 47), ("石嘴山", 49), ("沈阳", 50), ("苏州", 50), ("茂名", 50), ("嘉兴", 51), ("长春", 51), ("胶州", 52), ("银川", 52), ("张家港", 52), ("三门峡", 53), ("锦州", 54), ("南昌", 54), ("柳州", 54), ("三亚", 54), ("自贡", 56), ("吉林", 56), ("阳江", 57), ("泸州", 57), ("西宁", 57), ("宜宾", 58), ("呼和浩特", 58), ("成都", 58), ("大同", 58), ("镇江", 59), ("桂林", 59), ("张家界", 59), ("宜兴", 59), ("北海", 60), ("西安", 61), ("金坛", 62), ("东营", 62), ("牡丹江", 63), ("遵义", 63), ("绍兴", 63), ("扬州", 64), ("常州", 64), ("潍坊", 65), ("重庆", 66), ("台州", 67), ("南京", 67), ("滨州", 70), ("贵阳", 71), ("无锡", 71), ("本溪", 71), ("克拉玛依", 72), ("渭南", 72), ("马鞍山", 72), ("宝鸡", 72), ("焦作", 75), ("句容", 75), ("北京", 79), ("徐州", 79), ("衡水", 80), ("包头", 80), ("绵阳", 80), ("乌鲁木齐", 84), ("枣庄", 84), ("杭州", 84), ("淄博", 85), ("鞍山", 86), ("溧阳", 86), ("库尔勒", 86), ("安阳", 90), ("开封", 90), ("济南", 92), ("德阳", 93), ("温州", 95), ("九江", 96), ("邯郸", 98), ("临安", 99), ("兰州", 99), ("沧州", 100), ("临沂", 103), ("南充", 104), ("天津", 105), ("富阳", 106), ("泰安", 112), ("诸暨", 112), ("郑州", 113), ("哈尔滨", 114), ("聊城", 116), ("芜湖", 117), ("唐山", 119), ("平顶山", 119), ("邢台", 119), ("德州", 120), ("济宁", 120), ("荆州", 127), ("宜昌", 130), ("义乌", 132), ("丽水", 133), ("洛阳", 134), ("秦皇岛", 136), ("株洲", 143), ("石家庄", 147), ("莱芜", 148), ("常德", 152), ("保定", 153), ("湘潭", 154), ("金华", 157), ("岳阳", 169), ("长沙", 175), ("衢州", 177), ("廊坊", 193), ("菏泽", 194), ("合肥", 229), ("武汉", 273), ("大庆", 279)] geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center", width=1000, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 200], maptype='china', visual_text_color="#fff", symbol_size=10, is_visualmap=True) geo.render("全国主要城市空气质量.html") # 生成html文件
def test_full_example(): data = [("广州", 45), ("漳州", 35), ("A市", 43)] geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) coordinate = geo.get_coordinate("广州") assert 2 == len(coordinate) with assert_raises(ValueError): geo.get_coordinate("A市", raise_exception=True) attr, value = geo.cast(data) with assert_raises(ValueError): geo.add( "", attr, value, type="effectScatter", is_random=True, is_visualmap=True, is_piecewise=True, visual_text_color="#fff", pieces=[ { "min": 0, "max": 13, "label": "0 < x < 13" }, { "min": 14, "max": 16, "label": "14 < x < 16" }, ], effect_scale=5, ) geo.add_coordinate("A市", 119.3, 26.08) geo.add( "", attr, value, type="effectScatter", is_random=True, is_visualmap=True, is_piecewise=True, visual_text_color="#fff", pieces=[ { "min": 0, "max": 13, "label": "0 < x < 13" }, { "min": 14, "max": 16, "label": "14 < x < 16" }, ], effect_scale=5, ) geo.render()
def my_personal(): data=[('东莞',10),('深圳',20)] geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center", width=1000, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 200], maptype='china', visual_text_color="#fff", symbol_size=10, is_visualmap=True) geo.render("test.html") # 生成html文件
def keshihua(filepath): city = [] with io.open(filepath, mode='r', encoding='utf-8') as f: rows = f.readlines() for row in rows: try: city.append(row.split(' ')[1].replace('\n', '')) except: city.append('none') def all_list(arr): result = {} for i in set(arr): result[i] = arr.count(i) return result data = [] for item in all_list(city): data.append((item, all_list(city)[item])) style = Style(title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59") geo = Geo("王菊粉丝人群地理位置", "ZGM", **style.init_style) attr, value = geo.cast(data) print("data:", json.dumps(data, ensure_ascii=False)) print("attr:", json.dumps(attr, ensure_ascii=False)) print("value:", value) geo.add_coordinate(u"荷兰", 0, 0) geo.add_coordinate(u"马来西亚", 0, 0) geo.add_coordinate(u"越南", 0, 0) geo.add_coordinate(u"印度", 0, 0) geo.add_coordinate(u"希腊", 0, 0) geo.add_coordinate(u"昌都", 0, 0) geo.add_coordinate(u"none", 0, 0) geo.add_coordinate(u"新加坡", 0, 0) geo.add_coordinate(u"加拿大", 0, 0) geo.add_coordinate(u"澳大利亚", 0, 0) geo.add_coordinate(u"其他", 0, 0) geo.add_coordinate(u"美国", 0, 0) geo.add("", attr, value, visual_range=[0, 120], visual_text_color="#fff", symbol_size=20, is_visualmap=True, is_piecewise=True, visual_split_number=4) geo.render("fans_geo.html")
def test_geo_with_noexist_city(): data = [ ("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("伦敦", 15) ] geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(data) geo.add("", attr, value, type="effectScatter", is_random=True, effect_scale=5) geo.render()
def test_geo_guangdong_province(): data = [ ('汕头市', 50), ('汕尾市', 60), ('揭阳市', 35), ('阳江市', 44), ('肇庆市', 72) ] geo = Geo("广东城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(data) geo.add("", attr, value, maptype='广东', type="effectScatter", is_random=True, effect_scale=5, is_legend_show=False) geo.render()
def demo2(): from pyecharts import Geo data = [("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15)] geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, type="effectScatter", is_random=True, effect_scale=5) geo.show_config() geo.render()
def test_geo_shantou_city(): data = [ ('澄海区', 30), ('南澳县', 40), ('龙湖区', 50), ('金平区', 60) ] geo = Geo("汕头市地图示例", **style.init_style) attr, value = geo.cast(data) geo.add("", attr, value, maptype="汕头", is_visualmap=True, tooltip_formatter='{b}', is_legend_show=False, label_emphasis_textsize=15, label_emphasis_pos='right') geo.render()
def test_geo_china_effectscatter(): data = [ ("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15) ] geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(data) geo.add("", attr, value, type="effectScatter", is_random=True, effect_scale=5) assert '"type": "effectScatter"' in geo._repr_html_()
def test_geo_shantou_city(): data = [ ('澄海区', 30), ('南澳县', 40), ('龙湖区', 50), ('金平区', 60) ] geo = Geo("汕头市地图示例", **chart_init) attr, value = geo.cast(data) geo.add("", attr, value, maptype="汕头", is_visualmap=True, tooltip_formatter='{b}', is_legend_show=False, label_emphasis_textsize=15, label_emphasis_pos='right') geo.render()
def test_geo_guangdong_province(): data = [ ('汕头市', 50), ('汕尾市', 60), ('揭阳市', 35), ('阳江市', 44), ('肇庆市', 72) ] geo = Geo("广东城市空气质量", "data from pm2.5", **chart_init) attr, value = geo.cast(data) geo.add("", attr, value, maptype='广东', type="effectScatter", is_random=True, effect_scale=5, is_legend_show=False) geo.render()
def demo1(): data = [ ("海门", 9),("鄂尔多斯", 12),("招远", 12),("舟山", 12),("齐齐哈尔", 14),("盐城", 15), ("赤峰", 16),("青岛", 18),("乳山", 18),("金昌", 19),("泉州", 21),("莱西", 21), ("日照", 21),("胶南", 22),("南通", 23),("拉萨", 24),("云浮", 24),("梅州", 25)] geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center", width=1200, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 200], visual_text_color="#fff", symbol_size=15, is_visualmap=True) geo.show_config() geo.render()
def test_geo_china_scatter(): geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(cities) geo.add("", attr, value, visual_range=[0, 200], visual_text_color="#fff", is_legend_show=False, symbol_size=15, is_visualmap=True, tooltip_formatter='{b}', label_emphasis_textsize=15, label_emphasis_pos='right') html_content = geo._repr_html_() assert '"type": "scatter"' in html_content assert '"type": "heatmap"' not in html_content assert '"type": "effectScatter"' not in html_content
def test_geo_china_heatmap(): geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(cities) geo.add( "", attr, value, type="heatmap", is_visualmap=True, visual_range=[0, 300], visual_text_color="#fff", ) assert '"type": "heatmap"' in geo._repr_html_()
def test_geo_guangdong_province(): data = [("汕头市", 50), ("汕尾市", 60), ("揭阳市", 35), ("阳江市", 44), ("肇庆市", 72)] geo = Geo("广东城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(data) geo.add( "", attr, value, maptype="广东", type="effectScatter", is_random=True, effect_scale=5, is_legend_show=False, ) geo.render()
def test_geo_shantou_city(): data = [("澄海区", 30), ("南澳县", 40), ("龙湖区", 50), ("金平区", 60)] geo = Geo("汕头市地图示例", **style.init_style) attr, value = geo.cast(data) geo.add( "", attr, value, maptype="汕头", is_visualmap=True, tooltip_formatter="{b}", is_legend_show=False, label_emphasis_textsize=15, label_emphasis_pos="right", ) geo.render()
def draw_citys_pic(csv_file): page = Page(csv_file+":评论城市分析") info = count_city(csv_file) geo = Geo("","Ctipsy原创",title_pos="center", width=1200,height=600, background_color='#404a59', title_color="#fff") while True: # 二次筛选,和pyecharts支持的城市库进行匹配,如果报错则删除该城市对应的统计 try: attr, val = geo.cast(info) geo.add("", attr, val, visual_range=[0, 300], visual_text_color="#fff", is_geo_effect_show=False, is_piecewise=True, visual_split_number=6, symbol_size=15, is_visualmap=True) except ValueError as e: e = str(e) e = e.split("No coordinate is specified for ")[1] # 获取不支持的城市名称 info.pop(e) else: break info = sorted(info.items(), key=lambda x: x[1], reverse=False) # list排序 # print(info) info = dict(info) #list转dict # print(info) attr, val = [], [] for key in info: attr.append(key) val.append(info[key]) geo1 = Geo("", "评论城市分布", title_pos="center", width=1200, height=600, background_color='#404a59', title_color="#fff") geo1.add("", attr, val, visual_range=[0, 300], visual_text_color="#fff", is_geo_effect_show=False, is_piecewise=True, visual_split_number=10, symbol_size=15, is_visualmap=True, is_more_utils=True) #geo1.render(csv_file + "_城市dotmap.html") page.add_chart(geo1) geo2 = Geo("", "评论来源热力图",title_pos="center", width=1200,height=600, background_color='#404a59', title_color="#fff",) geo2.add("", attr, val, type="heatmap", is_visualmap=True, visual_range=[0, 50],visual_text_color='#fff', is_more_utils=True) #geo2.render(csv_file+"_城市heatmap.html") # 取CSV文件名的前8位数 page.add_chart(geo2) bar = Bar("", "评论来源排行", title_pos="center", width=1200, height=600 ) bar.add("", attr, val, is_visualmap=True, visual_range=[0, 100], visual_text_color='#fff',mark_point=["average"],mark_line=["average"], is_more_utils=True, is_label_show=True, is_datazoom_show=True, xaxis_rotate=45) #bar.render(csv_file+"_城市评论bar.html") # 取CSV文件名的前8位数 page.add_chart(bar) pie = Pie("", "评论来源饼图", title_pos="right", width=1200, height=600) pie.add("", attr, val, radius=[20, 50], label_text_color=None, is_label_show=True, legend_orient='vertical', is_more_utils=True, legend_pos='left') #pie.render(csv_file + "_城市评论Pie.html") # 取CSV文件名的前8位数 page.add_chart(pie) page.render(csv_file + "_城市评论分析汇总.html")
def demo3(): from pyecharts import Geo data = [ ("海门", 9), ("鄂尔多斯", 12), ("招远", 12), ("舟山", 12), ("齐齐哈尔", 14), ("盐城", 15), ("赤峰", 16), ("青岛", 18), ("乳山", 18), ("金昌", 19), ("泉州", 21), ("莱西", 21), ("日照", 21), ("胶南", 22), ("南通", 23), ("拉萨", 24), ("云浮", 24), ("梅州", 25), ("文登", 25), ("上海", 25), ("攀枝花", 25), ("威海", 25), ("承德", 25), ("厦门", 26), ("汕尾", 26), ("潮州", 26), ("丹东", 27), ("太仓", 27), ("曲靖", 27), ("烟台", 28), ("福州", 29), ("瓦房店", 30), ("即墨", 30), ("抚顺", 31), ("玉溪", 31), ("张家口", 31), ("阳泉", 31), ("莱州", 32), ("湖州", 32), ("汕头", 32), ("昆山", 33), ("宁波", 33), ("湛江", 33), ("揭阳", 34), ("荣成", 34), ("连云港", 35), ("葫芦岛", 35), ("常熟", 36), ("东莞", 36), ("河源", 36), ("淮安", 36), ("泰州", 36), ("南宁", 37), ("营口", 37), ("惠州", 37), ("江阴", 37), ("蓬莱", 37), ("韶关", 38), ("嘉峪关", 38), ("广州", 38), ("延安", 38), ("太原", 39), ("清远", 39), ("中山", 39), ("昆明", 39), ("寿光", 40), ("盘锦", 40), ("长治", 41), ("深圳", 41), ("珠海", 42), ("宿迁", 43), ("咸阳", 43), ("铜川", 44), ("平度", 44), ("佛山", 44), ("海口", 44), ("江门", 45), ("章丘", 45), ("肇庆", 46), ("大连", 47), ("临汾", 47), ("吴江", 47), ("石嘴山", 49), ("沈阳", 50), ("苏州", 50), ("茂名", 50), ("嘉兴", 51), ("长春", 51), ("胶州", 52), ("银川", 52), ("张家港", 52), ("三门峡", 53), ("锦州", 54), ("南昌", 54), ("柳州", 54), ("三亚", 54), ("自贡", 56), ("吉林", 56), ("阳江", 57), ("泸州", 57), ("西宁", 57), ("宜宾", 58), ("呼和浩特", 58), ("成都", 58), ("大同", 58), ("镇江", 59), ("桂林", 59), ("张家界", 59), ("宜兴", 59), ("北海", 60), ("西安", 61), ("金坛", 62), ("东营", 62), ("牡丹江", 63), ("遵义", 63), ("绍兴", 63), ("扬州", 64), ("常州", 64), ("潍坊", 65), ("重庆", 66), ("台州", 67), ("南京", 67), ("滨州", 70), ("贵阳", 71), ("无锡", 71), ("本溪", 71), ("克拉玛依", 72), ("渭南", 72), ("马鞍山", 72), ("宝鸡", 72), ("焦作", 75), ("句容", 75), ("北京", 79), ("徐州", 79), ("衡水", 80), ("包头", 80), ("绵阳", 80), ("乌鲁木齐", 84), ("枣庄", 84), ("杭州", 84), ("淄博", 85), ("鞍山", 86), ("溧阳", 86), ("库尔勒", 86), ("安阳", 90), ("开封", 90), ("济南", 92), ("德阳", 93), ("温州", 95), ("九江", 96), ("邯郸", 98), ("临安", 99), ("兰州", 99), ("沧州", 100), ("临沂", 103), ("南充", 104), ("天津", 105), ("富阳", 106), ("泰安", 112), ("诸暨", 112), ("郑州", 113), ("哈尔滨", 114), ("聊城", 116), ("芜湖", 117), ("唐山", 119), ("平顶山", 119), ("邢台", 119), ("德州", 120), ("济宁", 120), ("荆州", 127), ("宜昌", 130), ("义乌", 132), ("丽水", 133), ("洛阳", 134), ("秦皇岛", 136), ("株洲", 143), ("石家庄", 147), ("莱芜", 148), ("常德", 152), ("保定", 153), ("湘潭", 154), ("金华", 157), ("岳阳", 169), ("长沙", 175), ("衢州", 177), ("廊坊", 193), ("菏泽", 194), ("合肥", 229), ("武汉", 273), ("大庆", 279)] geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center", width=1000, height=600, background_color='#404a59') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 200], maptype='china', visual_text_color="#fff", symbol_size=10, is_visualmap=True) geo.render("全国主要城市空气质量.html") # 生成html文件
def test_full_example(): data = [("广州", 45), ("漳州", 35), ("A市", 43)] geo = Geo("全国主要城市空气质量", "data from pm2.5", **style.init_style) coordinate = geo.get_coordinate("广州") assert 2 == len(coordinate) with assert_raises(ValueError): geo.get_coordinate("A市", raise_exception=True) attr, value = geo.cast(data) with assert_raises(ValueError): geo.add( "", attr, value, type="effectScatter", is_random=True, is_visualmap=True, is_piecewise=True, visual_text_color="#fff", pieces=[ {"min": 0, "max": 13, "label": "0 < x < 13"}, {"min": 14, "max": 16, "label": "14 < x < 16"}, ], effect_scale=5, ) geo.add_coordinate("A市", 119.3, 26.08) geo.add( "", attr, value, type="effectScatter", is_random=True, is_visualmap=True, is_piecewise=True, visual_text_color="#fff", pieces=[ {"min": 0, "max": 13, "label": "0 < x < 13"}, {"min": 14, "max": 16, "label": "14 < x < 16"}, ], effect_scale=5, ) geo.render()
def test_geo_formatter_func(): style = Style( title_color="#fff", title_pos="center", width=1200, height=600, background_color="#404a59", ) data = [("汕头市", 50), ("汕尾市", 60), ("揭阳市", 35), ("阳江市", 44), ("肇庆市", 72)] geo = Geo("广东城市空气质量", "data from pm2.5", **style.init_style) attr, value = geo.cast(data) geo.add( "", attr, value, maptype="广东", type="effectScatter", tooltip_formatter=geo_formatter, is_random=True, effect_scale=5, is_legend_show=False, ) assert "function geo_formatter(" in geo._repr_html_()
# 全国城市地图示例 from pyecharts import Geo data = [ ("海门", 9),("鄂尔多斯", 12),("招远", 12),("舟山", 12),("齐齐哈尔", 14),("盐城", 15), ("惠州", 37),("江阴", 37),("蓬莱", 37),("韶关", 38),("嘉峪关", 38),("广州", 38), ("张家港", 52),("三门峡", 53),("锦州", 54),("南昌", 54),("柳州", 54),("三亚", 54), ("呼和浩特", 58),("成都", 58),("大同", 58),("镇江", 59),("桂林", 59),("张家界", 59), ("北京", 79),("徐州", 79),("衡水", 80),("包头", 80),("绵阳", 80),("乌鲁木齐", 84), ("菏泽", 194),("合肥", 229),("武汉", 273),("大庆", 279)] geo = Geo( "全国部分城市空气质量", title_color="#fff", title_pos="center", width=800, height=600, background_color="#404a59", ) attr, value = geo.cast(data) geo.add( "", attr, value, visual_range=[0, 200], visual_text_color="#fff", symbol_size=15, is_visualmap=True, ) geo.render('result.地理坐标系图.全国城市地图示例.html')
import datetime url = "http://www.86pm25.com/paiming.htm" head = { 'Referer': 'http://www.86pm25.com/city/Dazhou.html', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36' } html = requests.get(url, headers=head) html.encoding = 'utf-8' soup = BeautifulSoup(html.text, "lxml") data1 = soup.find(id="goodtable").find_all(name='a') data2 = str(soup.find(id='goodtable').find_all(name='td')) data = re.findall(r'<td>(\d{1,3}.)</td>', data2) with open("城市.txt", 'r') as f: CityList = f.read() city = [] for i in range(0, 367): if str(data1[i].string) in CityList: citytuple = (data1[i].string, int(data[i])) city.append(citytuple) geo = Geo("全国主要城市空气质量实时监控", "实时:" + str(datetime.datetime.now()), title_color="#fff", title_pos="center", width='100%', height=790, background_color='#404a59') attr, value = geo.cast(city) geo.add("", attr, value, visual_range=[0, 150], maptype='china', visual_text_color="#fff", symbol_size=13, is_visualmap=True) page = Page() page.add(geo) page.render("全国主要城市空气质量实时监控.html") webbrowser.open("全国主要城市空气质量实时监控.html", new=0, autoraise=True)