def take_snapshot(self, file_html=None, width="1400px", height="580px"): """获取快照 :param file_html: str 交易快照保存的 html 文件名 :param width: str 图表宽度 :param height: str 图表高度 :return: """ tab = Tab(page_title="{}@{}".format(self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M"))) for freq in self.freqs: chart = self.kas[freq].to_echarts(width, height) tab.add(chart, freq) t1 = Table() t1.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" in k and isinstance(v, str) and v not in ["Other~其他", "向下", 'Y~是', 'N~否', '向上']]) t1.set_global_opts(title_opts=ComponentTitleOpts(title="缠中说禅信号表", subtitle="")) tab.add(t1, "信号表") t2 = Table() ths_ = [["同花顺F10", "http://basic.10jqka.com.cn/{}".format(self.symbol[:6])]] t2.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" not in k and v != "Other~其他"] + ths_) t2.set_global_opts(title_opts=ComponentTitleOpts(title="缠中说禅因子表", subtitle="")) tab.add(t2, "因子表") if file_html: tab.render(file_html) else: return tab
def Create_Combine(my_data, ave_data, exam_name, class_data, grade_data, Exam_Number): #历次排名对比 tab = Tab() The_Line = Create_Line(class_data, grade_data) tab.add(The_Line, "历次排名") tab.add(table_base(), "参考上线排名") #不同考试成绩概况 t1 = Timeline() for i in range(len(ave_data)): Now_Bar = Create_Bar(my_data[i], ave_data[i], exam_name[i], "你的成绩", "平均分", False) t1.add(Now_Bar, exam_name[i]) tab.add(t1, "近段考试概况") #历次单科成绩对比 for i in range(0, 6): clone_score = [] for j in range(len(exam_name)): clone_score.append(my_data[j][i]) clone_rank = [] for j in range(len(exam_name)): clone_rank.append(All_Exam_RANK[j][i]) tab.add(Create_Line_RANK(clone_score, clone_rank), Subject[i]+"走势") tab.render(str(Exam_Number)+"的综合分析.html")
def multiple(): tab = Tab() tab.add(geo.set_map("confirmed",200000), "confirmed") tab.add(geo.set_map("deaths",30000), "deaths") tab.add(geo.set_map("recovered",90000), "recovered") tab.render(output_path+"tab_base.html") return True
def take_snapshot(self, file_html=None, width="1400px", height="580px"): """获取快照 :param file_html: str 交易快照保存的 html 文件名 :param width: str 图表宽度 :param height: str 图表高度 :return: """ tab = Tab(page_title="{}@{}".format( self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M"))) for freq in self.freqs: chart = ka_to_echarts(self.kas[freq], width, height) tab.add(chart, freq) t1 = Table() t1.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" in k]) t1.set_global_opts( title_opts=ComponentTitleOpts(title="缠中说禅信号表", subtitle="")) tab.add(t1, "信号表") t2 = Table() t2.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" not in k]) t2.set_global_opts( title_opts=ComponentTitleOpts(title="缠中说禅因子表", subtitle="")) tab.add(t2, "因子表") if file_html: tab.render(file_html) else: return tab
def test_tab_base(fake_writer): bar = _create_bar() line = _create_line() tab = Tab().add(bar, "bar-example").add(line, "line-example") tab.render() _, content = fake_writer.call_args[0] assert_in("bar-example", content) assert_in("line-example", content)
def tab_base(): tab = Tab() tab.add(bar_datazoom_slider(), "bar-example") tab.add(line_markpoint(), "line-example") tab.add(pie_rosetype(), "pie-example") tab.add(grid_mutil_yaxis(), "grid-example") tab.add(table_base(), "table-example") tab.render()
def tab_layout(list, title, name): tab = Tab() tab.add(death_histogram(list, title, name), "每日死亡") tab.add(CumulativeDeaths_histogram(list, title, name), '累计死亡') tab.add(Confirmed_histogram(list, title, name), "每日确诊") tab.add(CumulativeConfirmed_histogram(list, title, name), '累计确诊') tab.add(timeline(list, title, name), '时间轴') tab.render(name + '.html')
def main(): r = requests.get('http://127.0.0.1:5000/blocktree') print(r) data = r.json() with open("new_all_blocks.json", 'w') as file: json.dump(data, file, indent=2) file_ = "new_all_blocks.json" with open(file_, 'r') as file: file_data = json.load(file) blocks = file_data.values() num = 1 for block in blocks: block_info = block.values() for info in block_info: data = {} for i in info: if info[i]["attribute"] == "head": info[i]["attribute"] = 0 elif info[i]["attribute"] == "block": info[i]["attribute"] = 1 elif info[i]["attribute"] == "NORMAL": info[i]["attribute"] = 2 elif info[i]["attribute"] == "JUSTIFIED": info[i]["attribute"] = 3 elif info[i]["attribute"] == "FINALIZED": info[i]["attribute"] = 4 info[i].update({'x': 100, 'y': 800}) data['block'] = list(info.values()) with open("block%s.json" % num, 'w') as file1: json.dump(data, file1, indent=2) num += 1 tab = Tab() for i in range(1, num): same_height('block%s.json' % i) f = open('block%s.json' % i, ) data = json.load(f) nodes, edges, text = plot(data) categories = [ { "name": "head" }, { "name": "block" }, { "name": "normal checkpoint" }, { "name": "justified checkpoint" }, { "name": "finalized checkpoint" }] tab.add(datazoom_slider(nodes, edges, categories, text), "graph%s" % i) tab.render('blockchain.html')
def Gather(): tab = Tab(page_title='碧桂园集中式商业消费者满意度研究') CenterName, Data_Dict = CleanData() TabNames = list(Data_Dict.keys()) for TabName in TabNames: Scores_List = Data_Dict[TabName] tab.add(Satisfaction(CenterName, TabName, Scores_List), TabName) tab.add(NPS(CenterName), 'NPS') tab.render('满意度得分展示Demo.html')
def all(): tab = Tab(page_title='2019年安全公众号统计分析') tab.add(article_day_3d(), "公众号文章发布统计") tab.add(account_article_num(), "公众号收录文章数") tab.add(article_day_num(), "每天收录文章统计") tab.add(article_hour_num(), "文章发布时间段") tab.add(article_source_url(), "公众号文章来源") tab.add(zhaopin(), "公众号文章主题统计") tab.add(article_author(), "勤奋作者") tab.render(path='./static/year/2019.html') print('生成完毕')
def depLevels(): #获取处理后的依赖关系 depList = getDepList() timestr = str(datetime.datetime.now()) g1 = levelRender('request Levels Dependencies' + timestr, 'request', depList) g2 = levelRender('underscore Levels Dependencies' + timestr, 'underscore', depList) tab = Tab() tab.add(g1, "request") tab.add(g2, "underscore") tab.render("./templates/npmLevelDependencies.html")
def tab(filename="info"): ''' 分页组件 ''' tab = Tab() tab.add(liquid_data_precision("111"), "前日留存") tab.add(bar_datazoom_slider("222"), "分端留存") tab.add(table_base("222"), "明细") tab.add(line_markpoint("222"), "人群留存") tab.add(pie_rosetype("222"), "城市") tab.add(grid_mutil_yaxis("222"), "新增留存") tab.render_notebook() tab.render('{}.html'.format(filename))
def take_snapshot(self, file_html, width="950px", height="480px"): tab = Tab(page_title="{}的交易快照@{}".format( self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M"))) for freq in self.freqs: chart = ka_to_echarts(self.kas[freq], width, height) tab.add(chart, freq) headers = ["名称", "数据"] rows = [[k, v] for k, v in self.signals.items()] table = Table() table.add(headers, rows) table.set_global_opts( title_opts=ComponentTitleOpts(title="缠论信号", subtitle="")) tab.add(table, "信号表") tab.render(file_html)
def take_snapshot(self, file_html=None, width="1400px", height="580px"): """获取快照 :param file_html: str 交易快照保存的 html 文件名 :param width: str 图表宽度 :param height: str 图表高度 :return: """ tab = Tab(page_title="{}@{}".format( self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M"))) for freq in self.freqs: chart = self.kas[freq].to_echarts(width, height) tab.add(chart, freq) for freq in self.freqs: t1 = Table() t1.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if k.startswith("{}_".format(freq))]) t1.set_global_opts( title_opts=ComponentTitleOpts(title="缠中说禅信号表", subtitle="")) tab.add(t1, "{}信号表".format(freq)) t2 = Table() ths_ = [[ "同花顺F10", "http://basic.10jqka.com.cn/{}".format(self.symbol[:6]) ]] t2.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" not in k] + ths_) t2.set_global_opts( title_opts=ComponentTitleOpts(title="缠中说禅因子表", subtitle="")) tab.add(t2, "因子表") t3 = Table() t3.add(["本级别", "次级别"], [[k, v] for k, v in eval(self.s['级别映射']).items()]) t3.set_global_opts( title_opts=ComponentTitleOpts(title="缠中说禅级别映射表", subtitle="")) tab.add(t3, "级别映射表") if file_html: tab.render(file_html) else: return tab
def user_tab(data_set,user_id,title="用户数据分析"): """ :param data_set: :param user_id: :param title: :return: """ file_name = "user_data/" + str(user_id) + "_data.html" url = "cloud_" + str(user_id) + ".jpg" tab = Tab() tab.add(grid_recoder(data_set[0],user_id), "用户行为统计") tab.add(grid_like(data_set[1],user_id), "用户偏爱分析") # tab.add(page_plays(data_set[2],data_set[3],user_id), "用户习惯") tab.add(draw_bar_plays(data_set[2], user_id), "用户播放方式") tab.add(draw_line_clip(data_set[3], user_id), "片段播放频率统计") tab.add(draw_cloud(url, user_id), "歌词词云") tab.render(file_name)
def visualize_layer(model, image, layer_name, layer_max_image=32, jupyter=True, path='visualize_layer.html'): """network layer visualize. Args: model: a tf.keras model or keras model. image: a image array with shape (1, height, width, channel), height and width are necessary. layer_name: a list of model layers name. layer_max_image: every layer max plot images. jupyter: if plot in jupyter, default True. path: if jupyter is False, result save a html file. Returns: A pyecharts polt object. """ if tf.io.gfile.exists('feature_map'): tf.io.gfile.rmtree('feature_map') tf.io.gfile.makedirs('feature_map') if np.ndim(image)==2: image = tf.expand_dims(tf.expand_dims(image, 0), -1) elif np.ndim(image)==3: image = tf.expand_dims(image, 0) elif np.ndim(image)==4: pass else: raise ValueError('image shape is error.') temp_model = tf.keras.backend.function(model.inputs, [i.output for i in model.layers if i.name in layer_name]) temp_name = [i.name for i in model.layers if i.name in layer_name] result = temp_model(image) images_per_row = 16 count = 0 name_dict = {} tab = Tab() for feature, name in zip(result, temp_name): if feature.ndim==4: if feature.shape[-1]==3: display_grid = feature[0,:,:,:].astype('uint8') else: n_features = feature.shape[-1] if feature.shape[-1]<layer_max_image else layer_max_image size = feature.shape[1] n_cols = int(np.ceil(n_features/images_per_row)) display_grid = np.ones((size * n_cols, images_per_row * size),dtype=np.uint8)*255 for col in range(n_cols): for row in range(images_per_row): if (col+1)*(row+1)>n_features: break channel_image = feature[0, :, :, col * images_per_row + row] channel_image -= channel_image.mean() channel_image /= channel_image.std() channel_image *= 64 channel_image += 128 channel_image = np.clip(channel_image, 0, 255).astype('uint8') display_grid[col * size : (col + 1) * size, row * size : (row + 1) * size] = channel_image display_grid = np.expand_dims(display_grid, axis=-1) name_dict[name] = f'./feature_map/{count}.png' ImageAug(display_grid).save_image(name_dict[name]) tab.add(image_base(name_dict[name], name, 'shape='+str(feature.shape)), name) count += 1 return tab.render_notebook() if jupyter else tab.render(path)
def get_data(): file = open('数据.txt', "r", encoding="utf-8", errors="ignore") list = [] while True: mystr = file.readline() #表示一次读取一行 if not mystr: #读到数据最后跳出,结束循环。数据的最后也就是读不到数据了,mystr为空的时候 break data = json.loads(mystr) # print(data)#打印每次读到的内容 list.append(data) data = generate_data(list) tab = Tab() tab.add(bar_datazoom_slider(data), "北成上广深直方图") tab.add(line_markpoint(data), "北成上广深折线图") tab.add(pie_rosetype(data), "北成上广深饼状图") tab.add(table_base(data), "北成上广深成表格") tab.render("北上广深成15 in 1图.html")
def makechart(data, debug=False): day, shsum, shpending, shcured, shdeath, shsum_date, new_date, newconfirmed, newpending = data_process( data) title = "上海新型冠状病毒统计" grid_chart = Grid() grid_chart.add(total_trend(day, shdeath, shcured, shsum, shpending), grid_opts=GridOpts(height="57%")) grid_chart.add(new_trend(day, newconfirmed, newpending), grid_opts=GridOpts(pos_top="75%", )) bk = bkey() if debug: ak = bk.ak_dev else: ak = bk.ak_web get_detail() with open(shsumary, 'r', encoding='utf-8') as f: j = json.loads(f.read()) sumary = [(k, j[k]) for k in j.keys()] tab = Tab(page_title=title) tab.add(grid_chart, "趋势") tab.add(map_visualmap(sumary), "区县分布") tab.add(bmap_base(BAIDU_AK=ak), '详细地图') tab.render(outfile)
def plot_geo_summary(self, _geo_data, series_name=None, threshold_plot=None): ''' plot geo 经纬度聚类信息 :param geo_data: geo对应的城市分布(Series) :return: ''' self.series_name = series_name if series_name else self.series_name geo_data = np.array(list(dict(_geo_data).items())) self.threshold_plot = np.percentile( _geo_data, 80) if not threshold_plot else threshold_plot _geo = self.get_geo_base(geo_data) _map = self.get_map_base(geo_data) table = self.get_table_base(geo_data) tab = Tab(page_title=self.country, ) # 选项卡多图 tab.add(_map, "VisualMap") tab.add(_geo, "HeatMap") tab.add(table, "Data") tab.render(self.html_name)
def plot_summary(self, page_name='', page_type='page', web_open=False, html_name=None): assert page_type in ('page', 'tab'), '仅支持单页多图(page)和选项卡多图(tab)' if html_name: self.html_name = os.path.abspath(str(html_name) + '.html') if 'page' == page_type: page = Page(page_title=page_name) # 单页多图 for idata in self.datas: page.add(idata) page.render(self.html_name) else: tab = Tab(page_title=page_name, ) # 选项卡多图 for idata in self.datas: tab_name = idata.options.get('title').opts[0].get('text') tab.add(idata, tab_name) tab.render(self.html_name) if web_open: webbrowser.open(url='file://' + self.html_name, new=0, autoraise=True)
def visualize_heatmaps(model, image, layer_name, jupyter=True, path='visualize_heatmaps.html'): """network layer visualize. Args: model: a tf.keras model or keras model. image: a image array with shape (1, height, width, channel), height and width are necessary. layer_name: a list of model layers name. jupyter: if plot in jupyter, default True. path: if jupyter is False, result save a html file. Returns: A pyecharts polt object. """ if tf.io.gfile.exists('feature_map'): tf.io.gfile.rmtree('feature_map') tf.io.gfile.makedirs('feature_map') if np.ndim(image)==2: image = tf.expand_dims(tf.expand_dims(image, 0), -1) elif np.ndim(image)==3: image = tf.expand_dims(image, 0) elif np.ndim(image)==4: pass else: raise ValueError('image shape is error.') temp_model = tf.keras.backend.function(model.inputs, [i.output for i in model.layers if i.name in layer_name]) temp_name = [i.name for i in model.layers if i.name in layer_name] result = temp_model(image) images_per_row = 16 count = 0 name_dict = {} tab = Tab() for feature, name in zip(result, temp_name): if feature.ndim==4: if model.get_layer(name).__class__.__name__=='InputLayer': out = np.squeeze(image, 0).astype('uint8') else: out = tf.image.resize(tf.expand_dims(tf.squeeze(tf.reduce_sum(tf.abs(feature), axis=-1)), axis=-1), (image.shape[1], image.shape[2])) out = 255-tf.cast(out/tf.reduce_max(out)*255., tf.uint8) # print(np.squeeze(image, 0).shape) out = addWeighted(applyColorMap(out.numpy(), COLORMAP_JET), 0.7, np.squeeze(image, 0).astype('uint8'), 0.3, 0) # out = np.expand_dims(out, axis=-1) name_dict[name] = f'./feature_map/{count}.png' ImageAug(out).save_image(name_dict[name]) tab.add(image_base(name_dict[name], name, 'shape='+str(feature.shape)), name) count += 1 return tab.render_notebook() if jupyter else tab.render(path)
title_opts=opts.TitleOpts(title=name), )) return c def tab_add_html(tab, keys, datas, type): index = 1 for key in keys: tab.add(get_Line(key, datas[0], datas[index]), type + key) index = index + 1 if __name__ == "__main__": view = False while True: tab = Tab(js_host="./") keys, datas = read_log("_test_value.log", "Test net output ") tab_add_html(tab, keys, datas, "test-") keys, datas = read_log("_test_value.log", "Train net output ") tab_add_html(tab, keys, datas, "train-") tab.render("_test_value.html") print("update..") if view == False: view = True os.system("see _test_value.html &") time.sleep(10)
data1x.append(datarow[0]) # pyrcharts中横坐标要求为字符串,故不进行转换 bar1.add_xaxis(data1x) bar1.add_yaxis('A', data1y, label_opts=opt.LabelOpts(is_show=False)) bar1.set_global_opts( title_opts=opt.TitleOpts(title='柱状图示例'), ) bar2 = Bar() filename = 'hot-dog-places.csv' data2x = [] data2y = [] with open(filename) as f: reader = csv.reader(f) for datarow in reader: data2x.append(datarow) x2 = data2x[0] y21 = [float(x) for x in data2x[1]] y22 = [float(x) for x in data2x[2]] y23 = [float(x) for x in data2x[3]] bar2.add_xaxis(x2) bar2.add_yaxis('A', y21, stack=1) bar2.add_yaxis('B', y21, stack=1) bar2.add_yaxis('C', y21, stack=1) bar2.set_series_opts(label_opts=opt.LabelOpts(is_show=False)) tab.add(bar1, 'Bar') tab.add(bar2, 'Stack') tab.render('tab.html')
tl = Timeline(init_opts=opts.InitOpts(width="900px", height="500px")) for i in range(2015, 2020): bar = (Bar().add_xaxis(formatTimeList).add_yaxis( "商家A", Faker.values()).add_yaxis("商家B", Faker.values()).set_global_opts( title_opts=opts.TitleOpts("某商店{}年营业额".format(i)))) (tl.add(bar, "{}年".format(i)).add_schema(orient="horizontal", play_interval=500, symbol="circle", symbol_size=2, pos_bottom="-5px", height="37px")) return tl if __name__ == '__main__': title = "viewTimes" timestampList = [ '1578059280100', '1578059460100', '1578059640100', '1578059820100', '1578060000100', '1578060180100', '1578060360100' ] filePath = title + ".html" data1 = [465, 1488, 2474, 3951, 4903, 5345, 7304] data2 = [265, 1388, 2374, 3541, 4123, 5045, 7004] tab = Tab() tab.add(viewTime(timestampList, data1, data2), "viewTimes") tab.add(timeline_bar(timestampList, data1, data2), "Temp") tab.render(filePath)
def generate_city(city_list): input() china_province = {} for _province in province: china_province.update({_province: {}}) for x in city_list: if x[1] in province: china_province[x[1]].update({x[2]: [0, 0, 0]}) for item in city_list: name = item[1] if name in province: day = china_province[name][item[2]] # if name == '北京' or name == '上海' or name == '天津' or name == '重庆': # item[2] = item[2] + "区" # elif "自治" in name: # continue # else: # item[2] = item[2] + '市' china_province[name].update({ item[2]: [day[0] + item[3], day[1] + item[4], day[2] + item[5]] }) tab = Tab() for x in province: dict_province = china_province[x] confirm = [(k, v[0]) for k, v in dict_province.items()] if x == "湖北": _map = ( Map().add('确诊人数', confirm, x).set_series_opts( label_opts=opts.LabelOpts(is_show=True)). set_global_opts( title_opts=opts.TitleOpts(title="新型冠状病毒 {} 疫情地图".format(x), subtitle="更新时间:{}".format( city_list[-1][0])), legend_opts=opts.LegendOpts(is_show=True), visualmap_opts=opts.VisualMapOpts( is_show=True, max_=5000, is_piecewise=True, pieces=[ # 数据范围 { "min": 5000, "label": ">=5000", "color": "#807070" }, { "max": 4999, "min": 2000, "label": "2000 - 4999 人", "color": "#8B0000" }, { "max": 1999, "min": 1500, "label": "1500 - 1999 人", "color": "#CB0000" }, { "max": 1499, "min": 500, "label": "500 - 1499 人", "color": "#DD5C5C" }, { "max": 499, "min": 200, "label": "200 - 499 人", "color": "#FFA07A" }, { "max": 199, "min": 1, "label": "1 - 199 人", "color": "#FFFF00" }, ] # range_color=['#FFFFE0', '#FFA07A', '#CD5C5C', '#8B0000']) )) # .render("全国确诊.html") ) else: _map = ( Map().add('确诊人数', confirm, x).set_series_opts( label_opts=opts.LabelOpts(is_show=True)).set_global_opts( title_opts=opts.TitleOpts( title="新型冠状病毒 {} 疫情地图".format(x), subtitle="更新时间:{}".format(city_list[-1][0])), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts( is_show=True, max_=int(max([x[1] for x in confirm])), is_piecewise=True, range_color=[ '#FFFFE0', '#FFA07A', '#CD5C5C', '#8B0000' ])) # .render("全国确诊.html") ) tab.add(_map, x) # page.add(tab) tab.render(path="新型冠状病毒全国疫情地图.html")
def china_total(city_list): china_dict = {} # print(city_list) for name in province: china_dict.update({name: [0, 0, 0]}) for row in city_list: name = row[1] if name in province: day = china_dict[name] china_dict[name] = [ day[0] + row[3], day[1] + row[4], day[2] + row[5] ] print(china_dict) confirm = [(k, v[0]) for k, v in china_dict.items()] heal = [(k, v[1]) for k, v in china_dict.items()] dead = [(k, v[2]) for k, v in china_dict.items()] current_confirm = [(k, v[0] - v[1] - v[2]) for k, v in china_dict.items()] tab = Tab() _map = ( Map().add('确诊人数', confirm, "china").set_series_opts( label_opts=opts.LabelOpts(is_show=True)).set_global_opts( title_opts=opts.TitleOpts(title="新型冠状病毒全国疫情地图", subtitle="更新时间:{}".format( city_list[-1][0])), legend_opts=opts.LegendOpts(is_show=True), visualmap_opts=opts.VisualMapOpts( is_show=True, max_=1000, is_piecewise=True, pieces=[ # 数据范围 { "min": 10000, "label": ">=10000", "color": "#80707" }, { "max": 9999, "min": 1000, "label": "1000 - 9999 人", "color": "#8B0000" }, { "max": 999, "min": 500, "label": "500 - 999 人", "color": "#CB0000" }, { "max": 499, "min": 100, "label": "100 - 499 人", "color": "#DD5C5C" }, { "max": 99, "min": 10, "label": "10 - 99 人", "color": "#FFA07A" }, { "max": 9, "min": 1, "label": "1 - 9 人", "color": "#FFFF00" }, ] #range_color=['#FFFFE0', '#FFA07A', '#CD5C5C', '#8B0000']) )) # .render("全国确诊.html") ) tab.add(_map, "累计确诊") _map = ( Map().add('当前确诊人数', current_confirm, "china").set_series_opts( label_opts=opts.LabelOpts(is_show=True)).set_global_opts( title_opts=opts.TitleOpts(title="新型冠状病毒全国疫情地图", subtitle="更新时间:{}".format( city_list[-1][0])), legend_opts=opts.LegendOpts(is_show=True), visualmap_opts=opts.VisualMapOpts( is_show=True, max_=30, is_piecewise=True, range_color=['#FFFFE0', '#FFA07A', '#CD5C5C', '#8B0000'])) # .render("全国确诊.html") ) tab.add(_map, "当前确诊") _map = ( Map().add('当前治愈人数', heal, "china").set_series_opts( label_opts=opts.LabelOpts(is_show=True)).set_global_opts( title_opts=opts.TitleOpts(title="新型冠状病毒全国疫情地图", subtitle="更新时间:{}".format( city_list[-1][0])), legend_opts=opts.LegendOpts(is_show=True), visualmap_opts=opts.VisualMapOpts( is_show=True, max_=1500, is_piecewise=True, pieces=[ # 数据范围 { "min": 10000, "label": ">=10000", "color": "#143601" }, { "max": 9999, "min": 1000, "label": "1000 - 9999 人", "color": "#1A4301" }, { "max": 999, "min": 500, "label": "500 - 999 人", "color": "#245501" }, { "max": 499, "min": 300, "label": "300 - 499 人", "color": "#538D22" }, { "max": 299, "min": 100, "label": "100 - 299 人", "color": "#73A942" }, { "max": 99, "min": 0, "label": "1 - 99 人", "color": "#AAD576" }, ])) # .render("全国确诊.html") ) tab.add(_map, "累计治愈") _map = ( Map().add('当前死亡人数', dead, "china").set_series_opts( label_opts=opts.LabelOpts(is_show=True)).set_global_opts( title_opts=opts.TitleOpts(title="新型冠状病毒全国疫情地图", subtitle="更新时间:{}".format( city_list[-1][0])), legend_opts=opts.LegendOpts(is_show=True), visualmap_opts=opts.VisualMapOpts( is_show=True, max_=50, is_piecewise=True, range_color=['#FFFFE0', '#FFA07A', '#CD5C5C', '#8B0000'])) # .render("全国确诊.html") ) tab.add(_map, "累计死亡") tab.render(path="各省确诊人数.html")
if case["final_cheat"]: yes += 1 else: no += 1 case_oriented.append(yes) no_case_oriented.append(no) c = ( Bar() .add_xaxis(xaxis) .add_yaxis("面向用例题数", case_oriented, stack="stack1") .add_yaxis("正常完成题数", no_case_oriented, stack="stack1") .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts( title_opts=opts.TitleOpts(title="面向用例比例图"), yaxis_opts=opts.AxisOpts(name="题目数量"), xaxis_opts=opts.AxisOpts(name="用户ID"), datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], ) ) return c tab = Tab() tab.add(case_oriented(), "面向用例分布图") tab.add(bar_difficult(), "难度分布图") tab.add(scatter_debug_diff(), "字符串debug时间和难度点图") tab.add(wordcloud(), "tag词云图") tab.render("tab_summary.html")
offset=80, axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color="#5793f3")), axislabel_opts=opts.LabelOpts(formatter="{value} ml"), ), title_opts=opts.TitleOpts(title="Grid-多 Y 轴示例"), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), )) line = (Line().add_xaxis(x_data).add_yaxis( "平均温度", [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2], yaxis_index=2, color="#675bba", label_opts=opts.LabelOpts(is_show=False), )) bar.overlap(line) return Grid().add(bar, opts.GridOpts(pos_left="5%", pos_right="20%"), is_control_axis_index=True) tab = Tab() tab.add(bar_datazoom_slider(), "bar-example") tab.add(line_markpoint(), "line-example") tab.add(pie_rosetype(), "pie-example") tab.add(grid_mutil_yaxis(), "grid-example") tab.render("Tab_base.html")
# 计算未提交人数 df['已提交'] = df.apply(lambda x: x.value_counts().get(0, 0), axis=1) print(df) df['提交率'] = 1 - df.已提交 / (df.columns.size - 1) df['提交率'] = df['提交率'].apply(lambda x: format(x, '.2')) print(df.提交率) xaxis = [ '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1' ] for i in range(16): xaxis[i] = '第' + str(i + 1) + '次' print(xaxis) def line_xaxis_type() -> Line: c = (Line().add_xaxis(xaxis).add_yaxis( '1班_赵丽华', submission_rate(dfz)).add_yaxis( "4班_李烨", submission_rate(dfz)).set_global_opts( title_opts=opts.TitleOpts(title="正确率"), )) return c tab = Tab() tab.add(timeline_bar(), "作业平均分对比") tab.add(line_xaxis_type(), '作业提交率') tab.render()
def draw_charts(kline_data ,canshu ={} ,canshu2={},vol_bar=False,markline_show1 =False ,markline_show2 =False, path = '0501'): ''' df['candle_begin_time','open','high','low','close','volume'] [['candle_begin_time','open','high','low','close','volume']] kdata = df[['open', 'high', 'low', 'close']].values.tolist() df['candle_begin_time'].values.tolist() :return: ''' df = kline_data.copy() df['candle_begin_time'] = pd.to_datetime(df['candle_begin_time']) time_list = df['candle_begin_time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')).values.tolist() vol = df['volume'].values.tolist() kline = Kline() kline.add_xaxis(xaxis_data=time_list) signal_pos_list = [] if 'signal' in df.columns: print('signal,存在!') df['pos'] = df['signal'].shift(1) for i in df[df['pos'] > 0].index: bar0 = df.iloc[i] sig_pos0 = opts.MarkPointItem(name="做多", coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.low -2], value='买', symbol ='circle', symbol_size =[20,40], itemstyle_opts = {'color': 'red'}) signal_pos_list.append(sig_pos0) for i in df[df['pos'] < 0].index: bar0 = df.iloc[i] sig_pos0 = opts.MarkPointItem(name="做空", coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.high +3], value='卖', symbol='circle', symbol_size=[20, 40], itemstyle_opts={'color': 'blue'}) signal_pos_list.append(sig_pos0) for i in df[df['pos'] == 0].index: bar0 = df.iloc[i] sig_pos0 = opts.MarkPointItem(name="平仓", coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.low - 2], value='平', symbol ='triangle', symbol_size =[20,40], itemstyle_opts = {'color': 'green'}) signal_pos_list.append(sig_pos0) else : df['pos'] =None markline =[] if markline_show1 and ('signal' in df.columns) : area_index_list =[i for i in df[(df['pos'] ==0)|(df['pos'] >0)|(df['pos'] <0)].index] for ix,i in enumerate(area_index_list): if ix+1 > len(area_index_list)-1: break i_now = df.iloc[area_index_list[ix]] i_next = df.iloc[area_index_list[ix+1]] if (i_now['pos'] >0) or (i_now['pos'] <0) : log_info = f"价差:={i_next['open']-i_now['open']}--({i_next['open']}-{i_now['open']})" else : log_info =f"平仓:{i_next['open']}---开仓:{i_now['open']}" sig_area = [{"xAxis": i_now['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'] , "value": None}, {"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'], "value":log_info}] sig_area_v = [{"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'] , "value": None}, {"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_next['open'], "value":None}] markline.append(sig_area) markline.append(sig_area_v) elif markline_show2 and ('signal' in df.columns): area_index_list =[i for i in df[(df['pos'] ==0)|(df['pos'] >0)|(df['pos'] <0)].index] for ix,i in enumerate(area_index_list): i_now = df.iloc[area_index_list[ix]] i_1_now = df.iloc[area_index_list[ix-1]] if ix != 0 else 0 if i_now['pos'] == 0: log_info = f"交易价: {round(i_now['open'], 1)} +- 2__盈亏:{round(i_now['open'], 1) - round(i_1_now['open'], 1)}" else: log_info = f"交易价: {round(i_now['open'],1)} +- 2" sig_area = [{"xAxis": i_now['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'] , "value": None}, {"xAxis": (i_now['candle_begin_time']+timedelta(minutes=15)).strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'], "value":log_info}] markline.append(sig_area) colors = {'red': 'rgb((220,20,60)','red2': 'rgb((250,20,40)', 'yangzi': 'rgb(255,0,255)', 'zi': 'rgb(128,0,128)', 'sehnzi': 'rgb(148,0,211)', 'blue': 'rgb(0,0,255)', 'qing': 'rgb(0,255,255)', 'black': 'rgb(0,0,0)', 'shengreen': 'rgb(157,255,212)', 'green': 'rgb(0,255,0)', 'yellow': 'rgb(255,255,0)', 'glod': 'rgb(218,165,32)', 'orange': 'rgb(255,165,0)', 'brown': 'rgb(165,42,42)'} kline.add_xaxis(xaxis_data=time_list) kline.add_yaxis(series_name="oclh", xaxis_index=1, yaxis_index=1, y_axis =df.loc[:, ['open', 'close', 'low', 'high']].values.tolist(), markline_opts=opts.MarkLineOpts(data=markline, linestyle_opts=opts.LineStyleOpts(type_='dotted',width=3,color='red',opacity=0.5), label_opts=opts.LabelOpts(position="right", color="blue", font_size=13),), #官网给出的样本 markpoint_opts=opts.MarkPointOpts(data=signal_pos_list), itemstyle_opts=opts.ItemStyleOpts(color="#ec0090", color0="#00aa3c"), ) kline.set_global_opts( legend_opts=opts.LegendOpts(is_show=True,pos_top=30, pos_left="left",orient='vertical'), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1], range_start=90, range_end=100, orient='vertical'), opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1], type_="slider", pos_top="20%", range_start=90, range_end=100,orient='vertical'),], yaxis_opts =opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),), title_opts=opts.TitleOpts( title = 'K_line', pos_top='middle', title_textstyle_opts=opts.TextStyleOpts( color='black',font_weight='bold' ,font_size=20)), tooltip_opts=opts.TooltipOpts( trigger="axis", trigger_on='"mousemove"',#click|mousemove axis_pointer_type="cross", is_show_content=True, is_always_show_content=True, background_color="rgba(20, 105, 245, 0.1)", border_width=1, border_color= "#ccc", position = ['70%','30%'], textstyle_opts=opts.TextStyleOpts(font_size=10,color="#000"),), visualmap_opts=opts.VisualMapOpts( is_show=True, dimension=2, series_index=5, is_piecewise=True, pieces=[{"value": 1, "color": "#00da3c"},{"value": -1, "color": "#ec0000"},],), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{"xAxisIndex": "all"}], label=opts.LabelOpts(background_color="#777"),), brush_opts=opts.BrushOpts( x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX",), ) if len(canshu.keys())>0: cos = list(colors.values()) line = Line() for k,v in canshu.items(): line.add_xaxis(xaxis_data=time_list) line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category")) co = cos.pop() line.add_yaxis( series_name=k, y_axis = [y for y in v.values.tolist() if y != np.nan], xaxis_index=1, yaxis_index=1, is_smooth=False, is_connect_nones=False,# 是否连接空数据 is_symbol_show=False,#是否显示值的位置,默认显示。 color = co, is_hover_animation = False, # 是否开启 hover 在拐点标志上的提示动画效果。 linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9,color=co), label_opts=opts.LabelOpts(is_show =True,position='middle',distance=2,rotate=5,color = 'rgb(165,42,42)'), itemstyle_opts=opts.ItemStyleOpts(color=co),) kline = kline.overlap(line) grid_chart = Grid(init_opts=opts.InitOpts(width = "1500px",height= "700px",theme=ThemeType.DARK)) grid_chart.add(kline,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%",pos_top='4%' ,height="70%")) if( vol_bar == True) or (len(canshu2.keys())==0): bar = Bar() bar.add_xaxis(xaxis_data=time_list) bar.add_yaxis( series_name="volume", y_axis=vol, xaxis_index=1, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ) bar.set_global_opts(xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( grid_index=1, is_scale=True, split_number=2, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=True), ) grid_chart.add(bar,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="80%", height="15%"),) if len(canshu2.keys())>0 : line2 = Line() line2.add_xaxis(xaxis_data=time_list) for i, k in enumerate(canshu2.keys()): co = random.choice(list(colors.values())) line2.add_yaxis( series_name=k, y_axis=[y for y in canshu2[k].values.tolist()], xaxis_index=1, yaxis_index=i + 1, is_smooth=True, is_symbol_show=False, is_hover_animation=True, color=co, z_level=0, linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.5, color=co), label_opts=opts.LabelOpts(is_show=False), ) if k == list(canshu2.keys())[-1]: continue line2.extend_axis(yaxis=opts.AxisOpts(name=k, type_="value", position="right", min_=None, max_=None, axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color=co)), axislabel_opts=opts.LabelOpts(formatter="{value}"), )) line2.set_global_opts(xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, split_number=20, min_="dataMin", max_="dataMax", axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts(name=k, grid_index=i + 1, position='right', splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), min_=None, max_=None, is_scale=True, offset=50, ), ) grid_chart.add(line2,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="75%", height="23%"),is_control_axis_index=True) tab = Tab() zijin_data = (kline_data['per_lr'].cumsum()) zijin_data.fillna(method='ffill', inplace=True) zijin_line = Line(init_opts=opts.InitOpts(width = "1500px",height= "700px",theme=ThemeType.DARK)).add_xaxis(time_list) zijin_line.add_yaxis(series_name="zijin_line:", y_axis=zijin_data.values, color="#FF0000") zijin_line.set_global_opts( datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], title_opts=opts.TitleOpts(title="资金曲线变化"), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), yaxis_opts = opts.AxisOpts( is_scale=True, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts = opts.LegendOpts(is_show=True) ) tab.add(grid_chart,'kline' ) tab.add(zijin_line,'资金曲线变化' ) tab.render(f"{path}.html") html0 = tab.render(f"{path}.html") if os.path.exists(html0): print("ok!保存在:") print(html0) else: print('保存失败!')