def test_timeline_label_color(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add( "bar", attr, [randint(10, 50) for _ in range(6)], label_color=["red", "#213", "black"], ) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, "1 月") timeline.add(overlap_1, "2 月") content = timeline._repr_html_() assert '"color": [' in content assert "red" in content assert "#213" in content assert "black" in content
class MultiPlot: def __init__(self): self.data = '' self.timeLine = Timeline() self.page = Page() self.script_list = Bar().get_js_dependencies() def multi_plot(self, dat): self.data = dat try: for m_title, tpv1 in self.data.items(): self.timeLine = Timeline(is_auto_play=False, timeline_bottom=0) attr = tpv1['index'] for m_time in list(tpv1.columns): if m_time != 'index': tp_bar = Bar(m_time) tpv1 = tpv1.sort_values(by=m_time ,ascending=False) tp_bar.add(m_title, list(tpv1['index']), list(tpv1[m_time]), xaxis_interval=0, xaxis_rotate=30, yaxis_rotate=30,) self.timeLine.add(tp_bar, m_time) self.page.add(self.timeLine) return self.page.render_embed() except Exception as e: print('multi_plot error with {}'.format(str(e))) return None
def gen_gwzz_word(zwlb): qs = ZpWordByZwlbModel.objects if zwlb: qs = qs.filter(zwlb=zwlb) path = f'zp_word/{zwlb}.html' else: path = 'zp_word.html' df = read_frame(qs.all()) if len(df) > 0: page = Page() Grid_chart1 = Timeline(width=1500, height=800, timeline_bottom=0) df_group = df.groupby(['year', 'month']) for name, group in df_group: month = group['month'].tolist()[0] year = group['year'].tolist()[0] df_new = group.groupby('word').apply(get_echarts_all_by_value, 'word') chart = WordCloud(f'{zwlb}岗位需求词云', width=1500) shape_list = [ None, 'circle', 'cardioid', 'diamond', 'triangle-forward', 'triangle', 'pentagon', 'star' ] chart.add("", df_new['word'].tolist(), df_new['count'].tolist(), word_size_range=[30, 100], rotate_step=66, shape=shape_list[random.randint(0, len(shape_list) - 1)]) Grid_chart1.add(chart, f'{year}年{month}月') page.add(Grid_chart1) page.render(os.path.join(BASE_DIR, 'templates/{}'.format(path)))
def creatTimeLine(charts, timepoints, speed=500, showTimeLine=True): tt = Timeline(timeline_play_interval=speed, is_timeline_show=showTimeLine) cnt = 0 for chart in charts: tt.add(chart, time_point=timepoints[cnt]) cnt += 1 return tt
def test_timeline_pie(): style = Style() pie_style = style.add(is_label_show=True, radius=[30, 55], rosetype="radius") pie_1 = Pie("2012 年销量比例", "数据纯属虚构") pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_2 = Pie("2013 年销量比例", "数据纯属虚构") pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_3 = Pie("2014 年销量比例", "数据纯属虚构") pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_4 = Pie("2015 年销量比例", "数据纯属虚构") pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_5 = Pie("2016 年销量比例", "数据纯属虚构") pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) timeline = Timeline(is_auto_play=True, timeline_bottom=0, width=1200, height=600) timeline.add(pie_1, "2012 年") timeline.add(pie_2, "2013 年") timeline.add(pie_3, "2014 年") timeline.add(pie_4, "2015 年") timeline.add(pie_5, "2016 年") assert len(timeline._option.get("baseOption").get("series")) == 0 timeline.render()
def test_timeline_pie(): style = Style() pie_style = style.add(is_label_show=True, radius=[30, 55], rosetype="radius") pie_1 = Pie("2012 年销量比例", "数据纯属虚构") pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_2 = Pie("2013 年销量比例", "数据纯属虚构") pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_3 = Pie("2014 年销量比例", "数据纯属虚构") pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_4 = Pie("2015 年销量比例", "数据纯属虚构") pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_5 = Pie("2016 年销量比例", "数据纯属虚构") pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) timeline = Timeline(is_auto_play=True, timeline_bottom=0, width=1200, height=600) timeline.add(pie_1, '2012 年') timeline.add(pie_2, '2013 年') timeline.add(pie_3, '2014 年') timeline.add(pie_4, '2015 年') timeline.add(pie_5, '2016 年') timeline.render()
def _initial(self, speed): timeline = Timeline(width=self.width, height=self.height, timeline_play_interval=speed) index = 0 for bar in self.bars: timeline.add(bar, time_point=self.timePoints[index]) index += 1 return timeline
def test_timeline_pie(): style = Style() pie_style = style.add( is_label_show=True, radius=[30, 55], rosetype="radius" ) pie_1 = Pie("2012 年销量比例", "数据纯属虚构") pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_2 = Pie("2013 年销量比例", "数据纯属虚构") pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_3 = Pie("2014 年销量比例", "数据纯属虚构") pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_4 = Pie("2015 年销量比例", "数据纯属虚构") pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_5 = Pie("2016 年销量比例", "数据纯属虚构") pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) timeline = Timeline( is_auto_play=True, timeline_bottom=0, width=1200, height=600 ) timeline.add(pie_1, "2012 年") timeline.add(pie_2, "2013 年") timeline.add(pie_3, "2014 年") timeline.add(pie_4, "2015 年") timeline.add(pie_5, "2016 年") assert len(timeline.options.get("baseOption").get("series")) == 0 timeline.render()
def test_timeline_pie(): style = Style() pie_style = style.add( is_label_show=True, radius=[30, 55], rosetype="radius" ) pie_1 = Pie("2012 年销量比例", "数据纯属虚构") pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_2 = Pie("2013 年销量比例", "数据纯属虚构") pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_3 = Pie("2014 年销量比例", "数据纯属虚构") pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_4 = Pie("2015 年销量比例", "数据纯属虚构") pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) pie_5 = Pie("2016 年销量比例", "数据纯属虚构") pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style) timeline = Timeline(is_auto_play=True, timeline_bottom=0, width=1200, height=600) timeline.add(pie_1, '2012 年') timeline.add(pie_2, '2013 年') timeline.add(pie_3, '2014 年') timeline.add(pie_4, '2015 年') timeline.add(pie_5, '2016 年') timeline.render()
def test_null_in_timeline_options(): bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1._option["series"][0]["symbol"] = NULL timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, "2012 年") assert isinstance(timeline._option["options"][0]["series"][0]["symbol"], JsValue)
def gauge_timeline(data_array): chart1 = Timeline(**timeline_Style) array_gauge = [] for i in range(0, 13): array_gauge.append(data_array[i]['heat'].sum()) maxgauge = max(array_gauge) array_gauge = soomthByStage(array_gauge, 5) for i in range(0, 60): gauge = Gauge("观看人数趋势图 ", title_pos='center') gauge.add("", "占比", int(array_gauge[i] / maxgauge * 100)) chart1.add(gauge, String_filename_1[i]) return chart1
def show_map_school(begin_year, end_year): ''' 用地图展示各学校的排名,这样可以观察地域与学校排名的关系 ''' datas = deal_ruanke.ranking_ruanke(begin_year, end_year) university_name = (list)(datas.keys()) ranking_datas = (list)(datas.values()) timeline = Timeline(is_auto_play=False, timeline_bottom=0, width=stand_width, height=500) for i in range(begin_year, end_year + 1): data = [] dict = {} nan = '' for j in range(0, len(university_name)): line = [] line.append(university_name[j]) if (ranking_datas[j][i - begin_year] == "nan"): continue line.append(ranking_datas[j][i - begin_year]) line_tuple = (tuple)(line) data.append(line_tuple) dict[university_name[j]] = ranking_datas[j][i - begin_year] if (i == 2016): nan = "(云南大学,青海大学,西藏大学未纳入排名)" geo = Geo(str(i) + "年度全国大学排名" + nan, "全国大学排名", title_color="#000", title_pos="center", width=1600, height=400, background_color='#DCDCDC') attr, value = geo.cast(data) geo.add("", attr, value, visual_range=[0, 600], maptype='china', visual_text_color="#000", symbol_size=20, is_visualmap=True, is_roam=False, visual_top="center", geo_normal_color="#404a59", visual_range_text=["high", "low"], visual_range_color=['#50a3ba', '#faef61', '#d94e5d'], label_formatter="{c0}", tooltip_formatter="{b}: [经度(E),纬度(N),排名] {c}名") geo timeline.add(geo, str(i) + '年') return timeline
def test_timeline_bar_line(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add("bar", attr, [randint(10, 50) for _ in range(6)]) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) bar_2 = Bar("3 月份数据", "数据纯属虚构") bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_2 = Line() line_2.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_2 = Overlap() overlap_2.add(bar_2) overlap_2.add(line_2) bar_3 = Bar("4 月份数据", "数据纯属虚构") bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_3 = Line() line_3.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_3 = Overlap() overlap_3.add(bar_3) overlap_3.add(line_3) bar_4 = Bar("5 月份数据", "数据纯属虚构") bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_4 = Line() line_4.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_4 = Overlap() overlap_4.add(bar_4) overlap_4.add(line_4) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, '1 月') timeline.add(overlap_1, '2 月') timeline.add(overlap_2, '3 月') timeline.add(overlap_3, '4 月') timeline.add(overlap_4, '5 月') assert len(timeline._option.get("baseOption").get("series")) == 10 timeline.render()
def gen_zwyx_type(zwlb): qs = ZpZwyxByTypeModel.objects if zwlb: qs = qs.filter(zwlb=zwlb) path = f'zwyx_type/{zwlb}.html' else: path = 'zwyx_type.html' # 当月职位月薪与公司性质 df = read_frame(qs.all()) if len(df) > 0: page = Page() Grid_chart1 = Timeline(width=1500, height=450, timeline_bottom=0) Grid_chart2 = Timeline(width=1500, height=450, timeline_bottom=0) df_group = df.groupby(['year', 'month']) for name, group in df_group: month = group['month'].tolist()[0] year = group['year'].tolist()[0] df_new = group.groupby('type').apply(get_echarts_all_by_zwyx_value, 'type') # 薪资 Overlap_chart = Overlap(width=800, height=450) bar_chart = Bar(f'{zwlb}职位月薪与公司性质') bar_chart.add('最低薪资', df_new['type'].tolist(), df_new['min_zwyx'].tolist(), is_label_show=True, is_more_utils=True) bar_chart.add('最高薪资', df_new['type'].tolist(), df_new['max_zwyx'].tolist(), is_label_show=True, is_more_utils=True) line_chart = Line() line_chart.add("平均薪资", df_new['type'].tolist(), [(a + b) / 2 for a, b in zip(df_new['min_zwyx'].tolist(), df_new['max_zwyx'].tolist())], is_label_show=True) Overlap_chart.add(bar_chart) Overlap_chart.add(line_chart) Grid_chart1.add(Overlap_chart, f'{year}年{month}月') # 职位量 chart3 = Pie(f'{zwlb}职位量及招聘人数', width=1500) chart3.add('职位量'.format(zwlb), df_new['type'].tolist(), df_new['count'].tolist(), is_label_show=True, is_stack=True, center=[25, 50]) chart3.add('招聘人数'.format(zwlb), df_new['type'].tolist(), df_new['zprs'].tolist(), is_label_show=True, is_stack=True, center=[75, 50]) Grid_chart2.add(chart3, f'{year}年{month}月') page.add(Grid_chart1) page.add(Grid_chart2) page.render(os.path.join(BASE_DIR, 'templates/{}'.format(path)))
def gen_zwyx_dd(zwlb): qs = ZpZwByAreaModel.objects if zwlb: qs = qs.filter(zwlb=zwlb) path = f'zwyx_dd/{zwlb}.html' else: path = 'zwyx_dd.html' page = Page() df = read_frame(qs.all()) if len(df) > 0: df_group = df.groupby(['year', 'month']) time_line_chart1 = Timeline(width=1500, height=450, is_auto_play=False, timeline_bottom=0) time_line_chart2 = Timeline(width=1500, height=450, is_auto_play=False, timeline_bottom=0) for name, group in df_group: # 地图 平均薪资 month = group['month'].tolist()[0] year = group['year'].tolist()[0] df_new = group.groupby('province').apply( get_echarts_all_by_zwyx_value, 'province') data = [ (a, (b + c) / 2) for a, b, c in zip(df_new['province'].tolist( ), df_new['max_zwyx'].tolist(), df_new['min_zwyx'].tolist()) ] chart = Map(f'{zwlb}平均职位月薪与地点', width=1500, height=450) attr, value = chart.cast(data) chart.add(f'平均薪资', attr, value, wmaptype='china', is_label_show=True, is_visualmap=True, visual_range=[int(min(value)), int(max(value))], visual_pos='right', visual_top='top') time_line_chart1.add(chart, f'{year}年{month}月') # 本月职位量Top20 chart3 = Pie(f'{zwlb}职位量及招聘人数', width=1500) chart3.add('职位量', df_new['province'].tolist(), df_new['count'].tolist(), center=[25, 50], is_label_show=True) chart3.add('招聘人数', df_new['province'].tolist(), df_new['zprs'].tolist(), center=[75, 50], is_label_show=True) time_line_chart2.add(chart3, f'{year}年{month}月') page.add(time_line_chart1) page.add(time_line_chart2) page.render(os.path.join(BASE_DIR, 'templates/{}'.format(path)))
def test_timeline_map(): timeline = Timeline(timeline_bottom=0) value = [155, 10, 66, 78, 33, 80, 190, 53, 49.6] attr = ["福建", "山东", "北京", "上海", "甘肃", "新疆", "河南", "广西", "西藏"] map = Map("Map 结合 VisualMap 示例", width=1200, height=600) map.add( "", attr, value, maptype="china", is_visualmap=True, visual_text_color="#000", visual_top="30%", ) timeline.add(map, "test1") value = [155, 10, 66, 78, 33] attr = ["福建", "山东", "北京", "上海", "甘肃"] map = Map("Map 结合 VisualMap 示例", width=1200, height=600) map.add( "", attr, value, maptype="china", is_visualmap=True, visual_text_color="#000", visual_top="30%", ) timeline.add(map, "test2") assert len(timeline._option.get("baseOption").get("series")) == 2 timeline.render()
def test_timeline_bar_line(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add("bar", attr, [randint(10, 50) for _ in range(6)]) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) bar_2 = Bar("3 月份数据", "数据纯属虚构") bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_2 = Line() line_2.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_2 = Overlap() overlap_2.add(bar_2) overlap_2.add(line_2) bar_3 = Bar("4 月份数据", "数据纯属虚构") bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_3 = Line() line_3.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_3 = Overlap() overlap_3.add(bar_3) overlap_3.add(line_3) bar_4 = Bar("5 月份数据", "数据纯属虚构") bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_4 = Line() line_4.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_4 = Overlap() overlap_4.add(bar_4) overlap_4.add(line_4) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, "1 月") timeline.add(overlap_1, "2 月") timeline.add(overlap_2, "3 月") timeline.add(overlap_3, "4 月") timeline.add(overlap_4, "5 月") timeline.render()
def show_total_ruanke(begin_year, end_year): ''' 1.软科总体排名 @author: Hong wentao 最终的可视化结果呈现出的是2016年至今这14所学校在软科最好大学排名中的排名名次 ''' datas = deal_ruanke.ranking_ruanke(begin_year, end_year) university_name = (list)(datas.keys()) ranking_datas = (list)(datas.values()) timeline = Timeline(is_auto_play=False, timeline_bottom=0, width=stand_width) for i in range(0, end_year - begin_year + 1): bar = Bar("软科" + str(2016 + i) + "年大学排名数据") want_data = [] nan = '' before_median = [] for x in ranking_datas: want_data.append(x[i]) if x[i] == "nan": nan = "(如果某学校当年无数据,则该区域为为空白)" else: before_median.append(x[i]) a = np.array(before_median).astype("int") median = np.median(a).astype("int") bar.add("排名 " + nan, university_name, want_data, is_label_show=True, is_stack=True, xaxis_interval=0, xaxis_name_size=15, xaxis_rotate=0, yaxis_name_rotate=0, xaxis_name_pos="end", xaxis_name="学校名", yaxis_name="排名", yaxis_name_gap=10, yaxis_name_pos="end", mark_point=["max", "min"], mark_line_raw=[{ "yAxis": median, "name": "中位数", "lineStyle": { "color": 'black' } }]) timeline.add(bar, str(2016 + i) + ' 年') return timeline
def create_charts(): page = Page() style = Style(width=WIDTH, height=HEIGHT) df = pd.read_csv('./data_cleaned.csv') df['CREATE_TIME'] = pd.to_datetime(df['CREATE_TIME']) df['MONTH'] = 0 months = [] for i in df.CREATE_TIME: month = i.strftime("%Y-%m") months.append(month) df.MONTH = months chart = Timeline(is_auto_play=True, timeline_bottom=0, width=WIDTH, height=HEIGHT) for name, c in df.groupby('COMMUNITY_NAME'): month_count = defaultdict(int) for month, group in c.groupby('MONTH'): month_count[month] = len(group) m_s = sorted(list(month_count.keys())) m_l = [month_count[i] for i in m_s] chart_1 = Line("各月份社区事件数", **style.init_style) chart_1.add( "事件数", m_s, m_l, mark_point=["max", "min"], is_more_utils=True, mark_line=["average"], is_smooth=True, ) chart.add(chart_1, name) page.add(chart) chart = Timeline(is_auto_play=True, timeline_bottom=0, width=WIDTH, height=HEIGHT) for month, group in df.groupby('MONTH'): COMMUNITY_NAME = group.COMMUNITY_NAME.value_counts() chart_1 = Bar("各月份社区事件数", **style.init_style) chart_1.add("", COMMUNITY_NAME.index, COMMUNITY_NAME.values, mark_point=["max", "min"], mark_line=["average"], is_stack=True) chart.add(chart_1, month) page.add(chart) return page
def show_ruanke_best(begin_year,end_year): ''' @author: Hong wentao 用于展示每一个学科的学校的排名可视化,使用的是软科最好大学排名的数据 ''' path=data_path+"ruanke_best_subject/" ruanke_html_path=html_path+"ruanke/" isExists=os.path.exists(ruanke_html_path) if not isExists: os.makedirs(ruanke_html_path) first_names=os.listdir(path) for first_name in first_names: first_data_path=path+first_name+"/" first_html_path=ruanke_html_path+first_name+"/" isExists=os.path.exists(first_html_path) if not isExists: os.makedirs(first_html_path) second_names=os.listdir(first_data_path) for second_name in second_names: second_data_path=first_data_path+second_name+"/" second_html_path=first_html_path+second_name+"/" isExists=os.path.exists(second_html_path) if not isExists: os.makedirs(second_html_path) data=deal_ruanke.every_subject_ruanke(first_name,second_name) timeline = Timeline(is_auto_play=False, timeline_bottom=0,width=stand_width) for i in range(begin_year,end_year+1): bar = Bar(second_name+str(i)+"年大学排名数据") try: want_data=data[i] nan='空白区域说明该学校当年无该数据' final_data=[] have_name=[] before_median=[] for x in want_data: have_name.append(x[2]) for name in university_name: if name not in have_name: final_data.append("nan") else: for x in want_data: if x[2]==name: final_data.append(x[0]) before_median.append(x[0]) break; a=np.array(before_median).astype("int") median=np.median(a).astype("int") bar.add("排名 "+nan, university_name,final_data, is_label_show=True,is_stack=True,xaxis_interval=0,xaxis_name_size=15,xaxis_rotate=0,yaxis_name_rotate=0,xaxis_name_pos="end", xaxis_name="学校名",yaxis_name="排名",yaxis_name_gap=10,yaxis_name_pos="end",mark_point=["max","min"],mark_line_raw=[{"yAxis": median,"name":"中位数","lineStyle": { "color": 'black' }}]) timeline.add(bar, str(i)+'年') timeline.render(second_html_path+second_name+".html") except Exception: print(first_name+" "+second_name+str(i)+"没有") continue timeline.render(second_html_path+second_name+".html")
def test_timeline_map(): timeline = Timeline(timeline_bottom=0) value = [155, 10, 66, 78, 33, 80, 190, 53, 49.6] attr = ["福建", "山东", "北京", "上海", "甘肃", "新疆", "河南", "广西", "西藏"] map = Map("Map 结合 VisualMap 示例", width=1200, height=600) map.add( "", attr, value, maptype="china", is_visualmap=True, visual_text_color="#000", visual_top="30%", ) timeline.add(map, "test1") value = [155, 10, 66, 78, 33] attr = ["福建", "山东", "北京", "上海", "甘肃"] map = Map("Map 结合 VisualMap 示例", width=1200, height=600) map.add( "", attr, value, maptype="china", is_visualmap=True, visual_text_color="#000", visual_top="30%", ) timeline.add(map, "test2") assert len(timeline.options.get("baseOption").get("series")) == 2 timeline.render()
def flush_visual_data(): while True: timeline = Timeline(is_auto_play=True, timeline_bottom=0) cpudata = cpu(attr) memdata = mem(attr) diskdata = disk(attr) timeline.add(cpudata, 'CPU') timeline.add(memdata, '内存') timeline.add(diskdata, '磁盘') context = dict( visual_sysinfo=timeline.render_embed(), host=DEFAULT_HOST, script_list=timeline.get_js_dependencies(), ) context_json = json.dumps(context) with open('temp_json_info', 'wb') as temp_file: temp_file.write(context_json) time.sleep(600)
def create_charts(): page = Page() style = Style(width=WIDTH, height=HEIGHT) df = pd.read_csv('./data_cleaned.csv') STREET_NAME = df.STREET_NAME.value_counts() chart = Bar("街道种类", **style.init_style) chart.add( "", STREET_NAME.index, STREET_NAME.values, mark_point=["max", "min"], mark_line=["average"], is_stack=True, ) page.add(chart) chart = Timeline(is_auto_play=True, timeline_bottom=0, width=WIDTH, height=HEIGHT) for name, c in df.groupby('STREET_NAME'): EVENT_TYPE_NAME = c.EVENT_TYPE_NAME.value_counts() chart_1 = Bar("各社区事件类型", **style.init_style) chart_1.add("", EVENT_TYPE_NAME.index, EVENT_TYPE_NAME.values, mark_point=["max", "min"], mark_line=["average"], is_stack=True) chart.add(chart_1, name) page.add(chart) table = pd.pivot_table(df, index=['STREET_NAME'], columns=['EVENT_TYPE_NAME'], values=['SUB_TYPE_NAME'], aggfunc='count', fill_value=0, margins=1) table = table.ix[:-1, :-1] comm = list(table.index) name = [i[1] for i in table] value = [[i, j, float(table.values[i][j])] for i in range(len(comm)) for j in range(len(name))] chart = HeatMap("街道与事件热力图", width=WIDTH, height=HEIGHT) chart.add("", comm, name, value, is_visualmap=True, visual_text_color="#000", visual_orient='horizontal') page.add(chart) return page
def test_timeline_bar(): bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3 = Bar("2014 年销量", "数据纯属虚构") bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4 = Bar("2015 年销量", "数据纯属虚构") bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5 = Bar("2016 年销量", "数据纯属虚构") bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add( "冬季", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True, ) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, "2012 年") timeline.add(bar_2, "2013 年") timeline.add(bar_3, "2014 年") timeline.add(bar_4, "2015 年") timeline.add(bar_5, "2016 年") assert len(timeline._option.get("baseOption").get("series")) == 0 timeline.render()
def plot_bar_graph(): attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", attr, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季", attr, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季", attr, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季", attr, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季", attr, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季", attr, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季", attr, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季", attr, [randint(10, 100) for _ in range(6)]) bar_3 = Bar("2014 年销量", "数据纯属虚构") bar_3.add("春季", attr, [randint(10, 100) for _ in range(6)]) bar_3.add("夏季", attr, [randint(10, 100) for _ in range(6)]) bar_3.add("秋季", attr, [randint(10, 100) for _ in range(6)]) bar_3.add("冬季", attr, [randint(10, 100) for _ in range(6)]) bar_4 = Bar("2015 年销量", "数据纯属虚构") bar_4.add("春季", attr, [randint(10, 100) for _ in range(6)]) bar_4.add("夏季", attr, [randint(10, 100) for _ in range(6)]) bar_4.add("秋季", attr, [randint(10, 100) for _ in range(6)]) bar_4.add("冬季", attr, [randint(10, 100) for _ in range(6)]) bar_5 = Bar("2016 年销量", "数据纯属虚构") bar_5.add("春季", attr, [randint(10, 100) for _ in range(6)]) bar_5.add("夏季", attr, [randint(10, 100) for _ in range(6)]) bar_5.add("秋季", attr, [randint(10, 100) for _ in range(6)]) bar_5.add("冬季", attr, [randint(10, 100) for _ in range(6)], is_legend_show=True) timeline = Timeline(page_title=u'销量分析', is_auto_play=False, timeline_bottom=0) timeline.add(bar_1, '2012 年') timeline.add(bar_2, '2013 年') timeline.add(bar_3, '2014 年') timeline.add(bar_4, '2015 年') timeline.add(bar_5, '2016 年') timeline.render(FILE_DIR + 'bar_graph.html')
def draw_pie_all_cost(): _all = Account.objects.filter( # 让其显示最近六个月的数据 spent_date__gte=datetime(now().year, now().month, 1) - relativedelta( months=+5) # dateutil.relativedelata.relativedelta()偏移选择日期 ).values("spent_date", "reason").annotate(Sum("cost")) d = dict((i, list(j)) for i, j in groupby( _all, key=lambda x: (x['spent_date'].year, x['spent_date'].month))) timeline = Timeline(is_auto_play=False, timeline_bottom=0, width=800, height=500) # TODO:最大问题在于,如果有未显示的字段,会导致饼图颜色分类的不一致 # TODO: 开始展示折线图,然后点击折线图可以跳转 CHOICE = dict(Account.TAGS_CHOICE) # 名字 for k, v in d.items(): dict_cost = {} for _ in v: r = CHOICE[_['reason']] # 转换之后的*消费理由* c = _['cost__sum'] # 花费 if r in dict_cost: dict_cost[r] += c else: dict_cost[r] = c cost_pie = Pie( "{}年{}月".format(*k), "总开销{}元".format(sum(dict_cost.values()), width=800, height=100)) cost_pie.add("{}-{}".format(*k), dict_cost.keys(), dict_cost.values(), radius=[30, 75], is_label_show=True) timeline.add(cost_pie, "{}-{}".format(*k)) return timeline
def test_timeline_different_legend(): bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季b", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季b", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季b", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季b", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, '2012 年') timeline.add(bar_2, '2013 年') content = timeline._repr_html_() assert "\\u6625\\u5b63a" in content # 春季 a assert "\\u6625\\u5b63b" in content # 春季 b
def test_timeline_bar(): bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3 = Bar("2014 年销量", "数据纯属虚构") bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4 = Bar("2015 年销量", "数据纯属虚构") bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5 = Bar("2016 年销量", "数据纯属虚构") bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, '2012 年') timeline.add(bar_2, '2013 年') timeline.add(bar_3, '2014 年') timeline.add(bar_4, '2015 年') timeline.add(bar_5, '2016 年') timeline.render()
def spot_line(cnt,name): follow_spot=df[df['channel_id']==cnt] follow_spot=follow_spot.groupby(by=['spot_id','date'],as_index=False).sum()[['spot_id','date','cost_r']] spt=follow_spot[follow_spot['date'].apply(lambda x:str(x))==end_time.replace('-', '')].sort_values(by='cost_r').tail(7)['spot_id'] top_spt=follow_spot[follow_spot['spot_id'].isin(spt)] #TOP广告位 lists=[] for i,j in itertools.product(top_spt['spot_id'].drop_duplicates(),df['date'].drop_duplicates()): lists.append([i,j]) lists=pd.DataFrame(lists,columns=['spot_id','date']) top_spt=pd.merge(lists,top_spt,how='left',on=['spot_id','date']) top_spt=top_spt.fillna(0) top_spt=pd.merge(top_spt,meta_spot,how='left',left_on='spot_id',right_on='spotid') top_spt.loc[top_spt['name'].isnull(),'name']=top_spt[top_spt['name'].isnull()]['spot_id'] line = Line(name+'TOP广告位消耗') for i in top_spt['name'].drop_duplicates(): line.add(i,top_spt[top_spt['name']==i]['date'].apply(lambda x:str(x)),top_spt[top_spt['name']==i]['cost_r'].apply(lambda x:int(x)),legend_pos="84%",mark_point=['max']) # grid= Grid(width=1000,height=350) # grid.add(line,grid_right="25%") # page.add_chart(grid) ''' 涨跌幅TOP广告位 ''' lists=[] for i,j in itertools.product(follow_spot['spot_id'].drop_duplicates(),df['date'].drop_duplicates()): lists.append([i,j]) lists=pd.DataFrame(lists,columns=['spot_id','date']) follow_spt=pd.merge(lists,follow_spot,how='left',on=['spot_id','date'])#笛卡尔积 follow_spt=follow_spt.fillna(0) diff_spt=follow_spt.groupby(by='spot_id',as_index=False).diff()['cost_r'].rename('rise') diff_spt=pd.concat([follow_spt,diff_spt],axis=1) #涨幅TOP 7 spt=diff_spt[diff_spt['date'].apply(lambda x:str(x))==end_time.replace('-', '')].sort_values(by='rise').tail(7)['spot_id'] rise_spt=diff_spt[diff_spt['spot_id'].isin(spt)] #TOP广告位 rise_spt=pd.merge(rise_spt,meta_spot,how='left',left_on='spot_id',right_on='spotid') rise_spt.loc[rise_spt['name'].isnull(),'name']=rise_spt[rise_spt['name'].isnull()]['spot_id'] line1 = Line(name+'涨幅TOP广告位',width=1000,height=450) for i in rise_spt['name'].drop_duplicates(): line1.add(i,rise_spt[rise_spt['name']==i]['date'].apply(lambda x:str(x)),rise_spt[rise_spt['name']==i]['cost_r'].apply(lambda x:int(x)),legend_pos="84%") #跌幅TOP 7 spt=diff_spt[diff_spt['date'].apply(lambda x:str(x))==end_time.replace('-', '')].sort_values(by='rise').head(7)['spot_id'] fall_spt=diff_spt[diff_spt['spot_id'].isin(spt)] #TOP广告位 fall_spt=pd.merge(fall_spt,meta_spot,how='left',left_on='spot_id',right_on='spotid') fall_spt.loc[fall_spt['name'].isnull(),'name']=fall_spt[fall_spt['name'].isnull()]['spot_id'] line2 = Line(name+'跌幅TOP广告位',width=1000,height=450) for i in fall_spt['name'].drop_duplicates(): line2.add(i,fall_spt[fall_spt['name']==i]['date'].apply(lambda x:str(x)),fall_spt[fall_spt['name']==i]['cost_r'].apply(lambda x:int(x)),legend_pos="84%") #画图 grid= Grid(width=900,height=350) timeline = Timeline(timeline_bottom=0) timeline.add(line, name+'TOP消耗') timeline.add(line1, name+'涨幅TOP消耗') timeline.add(line2, name+'跌幅TOP消耗') grid.add(timeline) # grid= Grid(width=1200,height=350) # grid.add(line,grid_right="55%") # grid.add(line1,grid_left="55%") page.add_chart(grid)
def ShowNumWithYear(df): # show bus num in different year at different cities years = list(set(df['year'])) years.sort() cities = [] values = [] total_num = 0 geos = [] # store the geo every year timeline = Timeline(width=1500,height=800,is_auto_play=True, timeline_bottom=-10,timeline_symbol_size=20,\ timeline_play_interval = 800,timeline_left=20,timeline_right=100 , is_timeline_show = False ) for index in range(len(years)): df_temp = df[df['year'] == years[index]] cities = cities + list(df_temp['city']) values = values + list(df_temp['num']) total_num = sum(values) geos.append(Geo( str(years[index]) + " , Fist level title" , title_top = "10%" , title_text_size=50 , subtitle = "second level title" , \ subtitle_text_size = 23 , subtitle_color="white", \ title_color="red", title_pos="center", width=1200, height=600, \ background_color='#404a59')) # type="effectScatter", is_random=True, effect_scale=5 使点具有发散性 geos[index].add("数量", cities, values, type="effectScatter", maptype='china' , is_random=True, effect_scale=3, is_selected = True,is_toolbox_show = True ,is_more_utils =True,\ visual_text_color="#fff", symbol_size=10, is_label_show = True , legend_orient = 'left' ,is_legend_show = False, legend_top = 'bottom' , label_formatter = '{b}' , \ is_visualmap=True, is_roam=True , label_text_color="#00FF00" , is_piecewise=True, label_text_size = 7,visual_range=[1, 300] , \ geo_cities_coords = {'柯桥': [120.443 , 30.0822] ,} , \ pieces=[ {"min":0.1, "max": 500 , "label": "0-500"}, {"min": 500, "max": 1000 , "label": "501-1000"}, {"min": 1001, "max": 2000 , "label": "1001-2000"}, {"min":2001, "max": 5000, "label": "2001-5000"}, {"min":5001, "max": 100000, "label": ">5000"}, ] ) geos[index].show_config() geos[index].render("数量.html") # 时间轴定义 timeline.add(geos[index], years[index]) timeline.render('redult.html')
def test_timeline_bar(): bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3 = Bar("2014 年销量", "数据纯属虚构") bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4 = Bar("2015 年销量", "数据纯属虚构") bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5 = Bar("2016 年销量", "数据纯属虚构") bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add( "冬季", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True, ) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, "2012 年") timeline.add(bar_2, "2013 年") timeline.add(bar_3, "2014 年") timeline.add(bar_4, "2015 年") timeline.add(bar_5, "2016 年") assert len(timeline.options.get("baseOption").get("series")) == 0 timeline.render()
def get_pic(): a = order(df2,s.order_countJA,s.order_countHA,'') sz = order(df2,s.order_countJ,s.order_countH,s.shop_order,4)[0] gz = order(df2,s.order_countJ,s.order_countH,s.shop_order,42)[0] hz = order(df2,s.order_countJ,s.order_countH,s.shop_order,53)[0] hk = order(df2,s.order_countJ,s.order_countH,s.shop_order,85)[0] sh = order(df2,s.order_countJ,s.order_countH,s.shop_order,11)[0] bar_a = out_bar(a,"全国") bar_sz = out_bar(sz,"深圳") bar_gz = out_bar(gz,"广州") bar_hz = out_bar(hz,"杭州") bar_hk = out_bar(hk,"海口") bar_sh = out_bar(sh,"上海") timeline = Timeline(is_auto_play=False, timeline_bottom=0) timeline.add(bar_a, '全国') timeline.add(bar_sz, '深圳') timeline.add(bar_gz, '广州') timeline.add(bar_hz, '杭州') timeline.add(bar_hk, '海口') timeline.add(bar_sh, '上海') page = Page() page.add(timeline) page.render('{}数据图.html'.format(time.strftime("%Y%m%d", time.localtime())))
def bar1_timeline(data_array): pinghua = [[], [], [], [], [], [], [], [], [], []] chart = Timeline(**timeline_Style) for i in range(0, 13): bar1_timeline_data(data_array[i], pinghua) for i in range(0, 10): pinghua[i] = soomthByStage(pinghua[i], 5) pinghua_t = np.array(pinghua).T for i in range(0, 60): df = pd.DataFrame({'class': string_class_top10, 'heat': pinghua_t[i]}) bar = createBarFromDataFrame(dataFrame=df, xAxis="class", yAxis="heat", label="热度", title='top10热度变化趋势', titlePos='center', **bar_Style) chart.add(bar, String_filename_1[i]) return chart
def gen_zwyx_zw_count(zwlb): # 不同薪资的职位量和招聘人数分布 qs = ZpZwCountByZwyxModel.objects if zwlb: qs = qs.filter(zwlb=zwlb) path = f'zwyx_zw_count/{zwlb}.html' else: path = 'zwyx_zw_count.html' df = read_frame(qs.all()) if len(df) > 0: page = Page() Grid_chart1 = Timeline(width=1500, height=800, timeline_bottom=0) df_group = df.groupby(['year', 'month']) for name, group in df_group: month = group['month'].tolist()[0] year = group['year'].tolist()[0] df_new = group.groupby('zwyx').apply(get_echarts_all_by_zwyx_value, 'zwyx') # 薪资 bar_chart = Bar(f'{zwlb}招聘人数与职位量', width=1500) bar_chart.add('职位量', df_new['zwyx'].tolist(), df_new['count'].tolist(), is_label_show=True, datazoom_type="both", datazoom_range=[0, 5], is_datazoom_show=True) bar_chart.add('招聘人数'.format(zwlb), df_new['zwyx'].tolist(), df_new['zprs'].tolist(), is_label_show=True, datazoom_type="both", datazoom_range=[0, 5], is_datazoom_show=True) Grid_chart1.add(bar_chart, f'{year}年{month}月') page.add(Grid_chart1) page.render(os.path.join(BASE_DIR, 'templates/{}'.format(path)))
def test_timeline_different_legend(): bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季a", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季b", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季b", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季b", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add( "冬季b", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True, ) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, "2012 年") timeline.add(bar_2, "2013 年") content = timeline._repr_html_() assert "\\u6625\\u5b63a" in content # 春季 a assert "\\u6625\\u5b63b" in content # 春季 b
def graphpage(labels,mode_combo,startdate,enddate,optInterval,width1, height1): #optInterval='D/W/M' labels startdate = startdate.replace("/","-")#convert to tushare readable date enddate = enddate.replace("/","-") page = Page() for label in labels: # generate numbers of graphs according to numbers of queries in treewidget label1 = re.split("-", label) overlap = Overlap() if label1[2]!="分笔" and label1[2]!="季度饼图": #"K线" "复权" "历史分钟" if mode_combo == "复权": #if optInterval == "qfq" or optInterval == "hfq":#复权 array = ts.get_h_data(label1[1], start=startdate, end=enddate, autype="qfq") array = array.sort_index() time = array.index.format() # 日期正是index elif mode_combo == "K线": #elif optInterval.isalnum() :#历史K线 array = ts.get_k_data(label1[1], start=startdate, end=enddate, ktype=optInterval) time = array['date'].tolist() # array.date elif mode_combo == "历史分钟": array_bfr = ts.get_tick_data(label1[1], date=startdate) array_bfr.sort_values("time") a = startdate + " " + array_bfr["time"] array_bfr["time"] = a array_bfr["time"] = pd.to_datetime(a) array_bfr = array_bfr.set_index("time") if label1[2] != "Volume" and label1[2] != "Amount": price_df = array_bfr["price"].resample(optInterval).ohlc() # resample重新取样,选出ohlc=open/high/low,提取除价格之外另外4列.close,tushare是ohcl price_df = price_df.dropna() array = price_df time = price_df.index.format() elif label1[2] == "Volume": vols = array_bfr["volume"].resample(optInterval).sum() #resample重新取样,累加间隔内数值 relevant data processing algorithm taken from Jimmy, Creator of Tushare vols = vols.dropna() vol_df = pd.DataFrame(vols, columns=["volume"]) array = vol_df time = vol_df.index.format() else: amounts = array_bfr["amount"].resample(optInterval).sum() amounts = amounts.dropna() amount_df = pd.DataFrame(amounts, columns=["amount"]) array = amount_df time = amount_df.index.format() #绘图方法 if label1[2] == 'Kline': re_array = array[['open', 'close', 'high', 'low']] data_li = list(row.tolist() for index, row in re_array.iterrows()) # data_list = list(re_array.as_matrix()) close = array['close'].tolist() kline = Kline(label1[0] + "-" + optInterval, width=width1*10/11, height = (height1*10/11) / len(labels)) kline.add(label1[0], time, data_li, is_datazoom_show=True, datazoom_type="slider", yaxis_interval=1) overlap.add(kline) if len(close) > 10: ma10 = calculateMa(close, 10) line1 = Line(title_color="#C0C0C0") line1.add(label1[0] + "-" + "MA10", time, ma10) overlap.add(line1) if len(close) > 20: ma20 = calculateMa(close, 20) line2 = Line(title_color="#C0C0C0") line2.add(label1[0] + "-" + "MA20", time, ma20) overlap.add(line2) if len(close) > 30: ma30 = calculateMa(close, 30) line3 = Line(title_color="#C0C0C0") line3.add(label1[0] + "-" + "MA30", time, ma30) overlap.add(line3) page.add(overlap) else:#When label1[2]==open/close/volume if label1[2] == 'Open': list_aft = array['open'].tolist() elif label1[2] == 'Close': list_aft = close elif label1[2] == 'High': list_aft = array['high'].tolist() elif label1[2] == 'Low': list_aft = array['low'].tolist() elif label1[2] == 'Volume':#volume list_aft = array['volume'].tolist() else:#amount list_aft = array['amount'].tolist() line = Line(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels)) line.add(label1[0] + "-" + label1[2], time, list_aft, is_datazoom_show=True, yaxis_max="dataMax", yaxis_min="dataMin", datazoom_type="slider") overlap.add(line) page.add(overlap) elif label1[2]=="分笔": array = ts.get_tick_data(label1[1], date=startdate) array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() price = array["price"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): if val == "卖盘": amount[idx] = -amount[idx] if val == "中性盘": amount[idx] = 0 returnarray = list(zip(date, amount, flag, price)) form = [e[1] for e in returnarray] time = [d[0] for d in returnarray] bar = Bar(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels)) bar.add(label1[0] + "-" + label1[2], time, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax") overlap.add(bar) line = Line(label1[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels)) price = [e[3] for e in returnarray] line.add(label1[0] + "price", time, price, yaxis_min="dataMin", yaxis_max="dataMax", is_datazoom_show=True, datazoom_type="slider", yaxis_type="value") overlap.add(line, yaxis_index=1, is_add_yaxis=True) page.add(overlap) elif label1[2]=="季度饼图": datestr = startdate.split("-") thisyear = datestr[0] df2 = ts.top10_holders(code=label1[1], gdtype="1") test = df2[1]["quarter"].tolist() df_ready = df2[1] idxlist = [] for idx, val in enumerate(test): a = val.split("-") if a[0] == thisyear: # print a[0],idx idxlist.append(idx) thing = df_ready.loc[idxlist] thing = thing.sort_values(["quarter", "name"]) # print a[0],id name = thing["name"].tolist() value = thing["hold"].tolist() quarter = thing["quarter"].tolist() namearray = [name[i:i + 10] for i in range(0, len(name), 10)] valuearray = [value[j:j + 10] for j in range(0, len(value), 10)] quarterarray = [quarter[k:k + 10] for k in range(0, len(quarter), 10)] flag = ["pie" for i in namearray] num = [len(value) for k in namearray] returnarray = list(zip(namearray, valuearray, quarterarray, flag, num)) timeline = Timeline(is_auto_play=False, timeline_bottom=0) # zip(namearray,valuearray,quarter,flag,num) namearray = [c[0] for c in returnarray] valuearray = [d[1] for d in returnarray] quarter = [e[2] for e in returnarray] num = returnarray[0][4] for x in range(0, int(num / 10)): list1 = valuearray[x] names = namearray[x] quarters = quarter[x][0] for idx, val in enumerate(list1): list1[idx] = float(val) pie = Pie(label1[0] + "-" + "前十股东", width=width1 * 10 / 11, height=(height1 * 10 / 11)) pie.add(label1[0] + "-" + "前十股东", names, list1, radius=[30, 55], is_legend_show=False, is_label_show=True, label_formatter="{b}: {c}\n{d}%") timeline.add(pie, quarters) # namearray = [y for y in namearray[x]] timeline.render() page.render()
def graphpage(items,startdate,enddate,option,width1, height1): #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc page = Page() for i in items:#generate numbers of graphs according to numbers of queries in treewidget j = re.split("-",i) if len(j)==3: a = generateline(j[1],j[2],startdate,enddate,option)#stock number, Type, startdate, enddate, 30 or 15 or days if a is None: continue time = [d[0] for d in a]#get time from returned dictionary if j[2]!="Kline": if len(a[0])==4 and a[0][2]=="bar": #for 分笔data overlap = Overlap() form = [e[1] for e in a] bar = Bar(j[0] + "-" + j[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) bar.add(j[0] + "-" + j[2], time, form, yaxis_min = "dataMin",yaxis_max = "dataMax",is_datazoom_show = True, datazoom_type = "slider") overlap.add(bar) line = Line(j[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) price = [e[3] for e in a] line.add(j[0] + "price", time, price, yaxis_min = "dataMin",yaxis_max = "dataMax", is_datazoom_show = True, datazoom_type = "slider", yaxis_type="value") overlap.add(line,yaxis_index=1, is_add_yaxis=True) page.add(overlap) if len(a[0])==5 and a[0][3]=="pie": overlap = Overlap() timeline = Timeline(is_auto_play=False, timeline_bottom=0) #zip(namearray,valuearray,quarter,flag,num) namearray = [c[0] for c in a] valuearray = [d[1] for d in a] quarter = [e[2] for e in a] num = a[0][4] for x in range(0, num / 10): list1 = valuearray[x] names = namearray[x] quarters = quarter[x][0] for idx, val in enumerate(list1): list1[idx] = float(val) pie = Pie(j[0]+"-"+"前十股东".decode("utf-8"),width=width1 * 10 / 11, height=(height1 * 10 / 11)) pie.add(j[0]+"-"+"前十股东".decode("utf-8"), names, list1, radius=[30, 55], is_legend_show=False, is_label_show=True, label_formatter = "{b}: {c}\n{d}%") # print list # print names # print quarterarray timeline.add(pie, quarters) # namearray = [y for y in namearray[x]] timeline.render() return #need more statement else: form = [e[1] for e in a]#for not分笔 data line = Line(j[0] + "-" + j[2], width=width1*10/11, height=(height1*10/11)/len(items)) line.add(j[0] + "-" + j[2], time, form, is_datazoom_show=True, datazoom_type="slider",yaxis_min="dataMin",yaxis_max="dataMax") page.add(line) else: overlap = Overlap()#for k线 close = zip(*a)[2] candle = [[x[1], x[2], x[3], x[4]] for x in a] candlestick = Kline(j[0] + "-" + j[2], width=width1*10/11, height = (height1*10/11) / len(items)) candlestick.add(j[0], time, candle, is_datazoom_show=True, datazoom_type="slider",yaxis_interval = 1) overlap.add(candlestick) if len(close)>10: ma10 = calculateMa(close, 10) line1 = Line(title_color="#C0C0C0") line1.add(j[0] + "-" + "MA10", time, ma10) overlap.add(line1) if len(close)>20: ma20 = calculateMa(close, 20) line2 = Line(title_color="#C0C0C0") line2.add(j[0] + "-" + "MA20", time, ma20) overlap.add(line2) if len(close)>30: ma30 = calculateMa(close, 30) line3 = Line(title_color="#C0C0C0") line3.add(j[0] + "-" + "MA30", time, ma30) overlap.add(line3) page.add(overlap) else: for k in range(1, len(j)/3):#if graphs are combined j[3*k-1] = re.sub("\n&","",j[3*k-1]) sizearray=[] #if j[1] != "Candlestick" layout = Overlap() for i in xrange(0, len(j),3): array = j[i:i +3] b = generateline(array[1],array[2],startdate,enddate,option) if b is None: continue btime = [d[0] for d in b] if array[2] != "Kline": if len(b[0])==4 and b[0][2]=="bar": form = [e[1] for e in b] bar = Bar(array[0] + "-" + array[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) bar.add(array[0] + "-" + array[2], btime, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax") layout.add(bar) line = Line(array[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) price = [e[3] for e in b] line.add(array[0] + "price", btime, price, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_type="value") layout.add(line, yaxis_index=1, is_add_yaxis=True) else: line = Line(array[0] + "-" + array[2],width=width1*10/11, height=(height1*10/11) / len(items)) line.add(array[0]+"-"+array[2], btime, b, is_datazoom_show=True, yaxis_max = "dataMax", yaxis_min = "dataMin",datazoom_type="slider") layout.add(line) else: candle = [[x[1], x[2], x[3], x[4]] for x in b] candlestick = Kline(array[0] + "-" + array[1], width=width1*10/11, height=(height1*10/11) / len(items)) candlestick.add(array[0], btime, candle, is_datazoom_show=True, datazoom_type=["slider"]) #if i == 0: close = zip(*b)[2] if len(close)>10: ma10 = calculateMa(close, 10) line4 = Line(title_color="#C0C0C0") line4.add(array[0] + "-" + "MA10", btime, ma10) layout.add(line4) if len(close)>20: ma20 = calculateMa(close, 20) line5 = Line(title_color="#C0C0C0") line5.add(array[0] + "-" + "MA20", btime, ma20) layout.add(line5) if len(close)>30: ma30 = calculateMa(close, 30) line6 = Line(title_color="#C0C0C0") line6.add(array[0] + "-" + "MA30", btime, ma30) layout.add(line6) layout.add(candlestick) page.add(layout) page.render()
def test_page_grid_timeline_overlap(): # Grid v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图示例", height=720, width=1200, title_pos="65%") bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True, legend_pos="80%") line = Line("折线图示例") line.add( "最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"], ) line.add( "最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"], mark_line=["average"], legend_pos="20%", ) v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] scatter = Scatter("散点图示例", title_top="50%", title_pos="65%") scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%") es = EffectScatter("动态散点图示例", title_top="50%") es.add( "es", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0], effect_scale=6, legend_top="50%", legend_pos="20%", ) grid = Grid() grid.add(bar, grid_bottom="60%", grid_left="60%") grid.add(line, grid_bottom="60%", grid_right="60%") grid.add(scatter, grid_top="60%", grid_left="60%") grid.add(es, grid_top="60%", grid_right="60%") # Timeline bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3 = Bar("2014 年销量", "数据纯属虚构") bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4 = Bar("2015 年销量", "数据纯属虚构") bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5 = Bar("2016 年销量", "数据纯属虚构", height=720, width=1200) bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add( "冬季", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True, ) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, "2012 年") timeline.add(bar_2, "2013 年") timeline.add(bar_3, "2014 年") timeline.add(bar_4, "2015 年") timeline.add(bar_5, "2016 年") # Overlap attr = ["{}月".format(i) for i in range(1, 13)] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2] bar = Bar(height=720, width=1200) bar.add("蒸发量", attr, v1) bar.add("降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) page = Page() page.add(grid) page.add(timeline) page.add(overlap) page.render()