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
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 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)
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_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_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 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 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_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 get_pic(): df2 = shops(mob_site)[1] a = order(df2, order_countJA, order_countHA, '') sz = order(df2, order_countJ, order_countH, shop_order, 4)[0] gz = order(df2, order_countJ, order_countH, shop_order, 42)[0] hz = order(df2, order_countJ, order_countH, shop_order, 53)[0] hk = order(df2, order_countJ, order_countH, shop_order, 85)[0] sh = order(df2, order_countJ, order_countH, shop_order, 11)[0] cs = order(df2, order_countJ, order_countH, shop_order, 205)[0] fz = order(df2, order_countJ, order_countH, shop_order, 201)[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, "上海") bar_cs = out_bar(cs, "长沙") bar_fz = out_bar(fz, "福州") timeline = Timeline(is_auto_play=False, timeline_bottom=0, width=1100) timeline.add(bar_a, '全国') timeline.add(bar_sz, '深圳') timeline.add(bar_gz, '广州') timeline.add(bar_hz, '杭州') timeline.add(bar_hk, '海口') timeline.add(bar_sh, '上海') timeline.add(bar_cs, '长沙') timeline.add(bar_fz, '福州') return timeline
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 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_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 time_line(): timeline = Timeline(page_title="Time Line") stack_bar, line = StackBar.stack_bar() tree_chart = TreeChart.tree_chart() stack_bar_chart = StackBarChart.stack_bar_chart2() stack_line = StackChart.starck_line_chart() timeline.add(stack_line, time_point=7) timeline.add(stack_bar_chart, time_point=8) timeline.add(tree_chart, time_point=6) timeline.add(stack_bar,time_point=2) timeline.add(line, time_point=3) timeline.render("timeline.html")
def geographical_location_GDP_ratio_distribution(): data = pd.read_excel("./data/car_sales_data.xlsx", sheet_name=u"人均GDP", encoding='utf-8') data.columns = [str(col).split('-')[0] for col in data.columns] float_cols = [str(year) for year in range(1998, 2018)] not_replace = [ u'池州市', u'宣城市', u'眉山市', u'达州市', u'庆阳市', u'广安市', u'贺州市', u'来宾市', u'崇左市', u'临沧市', u'固原市', u'中卫市', u'丽江市' ] data['city_name'] = data['city_name'].apply(lambda xx: xx.replace(u'市', '') if xx not in not_replace else xx) city_none = [u'黔西南布依族苗族自治州', u'乌兰察布', u'巴音郭楞蒙古自治州(库尔勒)'] data = data[~data['city_name'].isin(city_none)] data[float_cols] = data[float_cols].fillna(0).applymap(lambda xx: round(xx, 2) if xx else 0) cols_show = ['city_name'] + float_cols data = data[cols_show] data = calc_ratio_percent(data) data[range(1999, 2018)] = data[range(1999, 2018)].applymap(lambda xx: round(xx * 100, 2)) data.to_excel('./car_sales_visualization/GDP_ratio_distribution.xlsx') timeline = Timeline(is_auto_play=False, timeline_bottom=1250, width=2480, height=1330) for year in range(1999, 2018): dataset = [(city, sales) for city, sales in data[['city_name'] + [year]].values] geo = Geo( "%s - Car Sales Num Ratio Distribution" % year, "", title_pos="center", title_color="black", width=2480, height=1330, background_color='#ffffff' ) attr, value = geo.cast(dataset) geo.add( "", attr, value, type="effectScatter", is_visualmap=True, maptype='china', visual_range=[-100.0, 100.0], visual_text_color="black", effect_scale=5, symbol_size=5 ) timeline.add(geo, year) timeline.render('./car_sales_visualization/GDP_ratio_distribution.html')
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 geographical_location_ratio_distribution(): data = pd.read_csv("./data/car_sales_volume_data.csv", encoding='utf-8') data = data[data['city'].str.len() > 1] data = calc_ratio_percent(data) data[range(1998, 2019)] = data[range(1998, 2019)].applymap(lambda xx: round(xx * 100, 4)) cols_show = ['city'] + range(1998, 2019) data = data[cols_show] city_none = [ u'三沙', u'中卫', u'临沧', u'丽江', u'克孜勒苏柯尔克孜自治州', u'其它', u'固原', u'新疆自治区直辖', u'普洱', u'河南省省直辖', u'海南省省直辖', u'湖北省省直辖' ] data = data[~data['city'].isin(city_none)] data.to_excel('./car_sales_visualization/car_sales_num_ratio.xlsx') timeline = Timeline(is_auto_play=False, timeline_bottom=1250, width=2480, height=1330) for year in range(1998, 2019): dataset = [(city, sales) for city, sales in data[['city'] + [year]].values] geo = Geo( "%s - Car Sales Num Ratio Distribution" % year, "", title_pos="center", title_color="black", width=2480, height=1330, background_color='#ffffff' ) attr, value = geo.cast(dataset) geo.add( "", attr, value, type="effectScatter", is_visualmap=True, maptype='china', visual_range=[-100, 100], visual_text_color="black", effect_scale=5, symbol_size=5 ) timeline.add(geo, year) timeline.render('./car_sales_visualization/car_sales_num_ratio.html')
def get_html_project_report(project_name, type=0): mylogger = common.LogOutput.Log().get_logger() mylogger.info( "------------------------------------------------------------------") mylogger.info("当前运行文件:{}".format(__file__)) try: project_run_num = get_project_run_num(project_name, type) # num = [successNum, failedNum, noRunNum] num = [project_run_num[0], project_run_num[1], project_run_num[2]] attr = ["成功用例", "失败用例", "不执行用例"] bar = Bar(project_name, "用例执行结果") bar.add("", attr, num, is_more_utils=True) bar.show_config() pie_1 = Pie(project_name, "用例执行结果") pie_1.add(project_name, attr, num, is_label_show=True, radius=[30, 55], rosetype='radius') timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar, '树形图') timeline.add(pie_1, '饼形图') PATH = lambda P: os.path.abspath( os.path.join(os.path.dirname(__file__), P)) html_dirname = PATH( "../report") + "\\" + project_name + "\\" + "htmlReport\\" # 判断是否存在case目录,没有,则创建 if not os.path.exists(html_dirname): os.mkdir(html_dirname) mylogger.info("生成用例目录路径:{}".format(html_dirname)) if type == 0: html_report_name = time.strftime('%Y-%m-%d %H-%M-%S') + '.html' elif type == 1: html_report_name = 'settingReport' + time.strftime( '%Y-%m-%d %H-%M-%S') + '.html' htmlReportPath = html_dirname + html_report_name timeline.render(htmlReportPath) return 'success' except TypeError as e: return 'caseEmpty', e
def geographical_location_amount_distribution(): data = pd.read_csv("./data/car_sales_volume_data.csv", encoding='utf-8') data = data[data['city'].str.len() > 1] city_none = [ u'三沙', u'中卫', u'临沧', u'丽江', u'克孜勒苏柯尔克孜自治州', u'其它', u'固原', u'新疆自治区直辖', u'普洱', u'河南省省直辖', u'海南省省直辖', u'湖北省省直辖' ] data = data[~data['city'].isin(city_none)] int_cols = [str(col) for col in range(1998, 2019)] data[int_cols] = data[int_cols].applymap(lambda xx: float(xx)) timeline = Timeline(is_auto_play=False, timeline_bottom=1250, width=2480, height=1330) for year in range(1998, 2019): dataset = [(city, sales) for city, sales in data[('city %s' % year).split()].values] print dataset geo = Geo( "%s - Car Sales Num Amount Distribution" % year, "", title_pos="center", title_color="black", width=2700, height=1340, background_color='#ffffff' ) attr, value = geo.cast(dataset) geo.add( "", attr, value, maptype='china', visual_range=[0, 300000], visual_text_color="black", type="heatmap", is_visualmap=True, effect_scale=5, symbol_size=5, ) timeline.add(geo, year) timeline.render('./car_sales_visualization/car_sales_num_amount.html')
def bar_map(): kwargs = dict( label_text_color=None, is_label_show=True, legend_orient='vertical', legend_pos='right', legend_top='center', legend_selectedmode='single', legend_text_size=18, label_text_size=18, label_emphasis_textsize=18, xaxis_name_size=18, xaxis_label_textsize=18, xaxis_margin=5, xaxis_line_width=2, yaxis_name_size=18, yaxis_label_textsize=18, bar_category_gap=25, yaxis_line_width=2, is_splitline_show=False, is_xaxis_boundarygap=True, is_toolbox_show=False, ) timeline = Timeline(timeline_bottom=0, width=1400, height=700, timeline_symbol_size=10) for year in value_base.current_years: bar = Bar('村镇对比图', title_pos='center', title_text_size=30, title_top=10) for index in value_base.current_indexs: data = [] for i in value_base.current_areas: for veti_data in value_base.veti_data_dict[year]: if veti_data[0] == i: data.append( veti_data[value_base.index_num_dict[index]]) bar.add(index, value_base.current_areas, data, **kwargs) timeline.add(bar, year) result = str(value_base.output_dir + u"村镇对比.html") timeline.render(result)
def radar_map(): kwargs = dict(label_text_color=None, is_label_show=True, legend_orient='vertical', legend_pos='right', legend_top='center', legend_text_size=18, label_text_size=18, label_emphasis_textsize=18, xaxis_name_size=18, xaxis_label_textsize=18, xaxis_margin=5, xaxis_line_width=2, yaxis_name_size=18, yaxis_label_textsize=18, yaxis_line_width=2, is_splitline_show=False, is_xaxis_boundarygap=True, is_toolbox_show=False, line_width=3) timeline = Timeline(timeline_bottom=0, width=1400, height=700, timeline_symbol_size=10) for year in value_base.current_years: radar_map = Radar('雷达图', title_pos='center', title_text_size=30, title_top=10) for area in value_base.current_areas: data = [[]] for index in value_base.current_indexs: for veti_data in value_base.veti_data_dict[year]: if veti_data[0] == area: data[0].append( round(veti_data[value_base.index_num_dict[index]], 2)) radar_map.set_radar_component(schema=value_base.radar_schema) radar_map.add(area, data, **kwargs) timeline.add(radar_map, year) result = str(value_base.output_dir + u"雷达图.html") timeline.render(result)
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 dashboard_loan_amount(): '''添加放款金额轮播图表''' # 生成图表实例 timeline = Timeline(is_auto_play=True, timeline_bottom=0, width="100%") # 使用暗色主题 timeline.use_theme('dark') # 生成每个月份的图表 for month in months: # X轴label n_day_in_month = pd.Period(month+"-01").days_in_month attr = list(range(1,n_day_in_month+1)) # 图表数据 v1 = list(np.random.randint(2000, 10000, n_day_in_month) / 10) # 生成图表实例 chart = Line("%s月放款金额走势图" %month,"当月放款总金额为%.2f万" %np.sum(v1), background_color=BACKGROUND_COLOR, width="100%") # 使用暗色主题 chart.use_theme('dark') # 载入默认设置并差异化更新 chart_kwargs = DEFAULT_KWARGS chart_kwargs.update({ "xaxis_interval":0, "mark_line": ["average"], "is_smooth": True, "is_fill": True, "area_opacity": 0.3, }) # 添加数据 chart.add("放款金额", attr, v1, **chart_kwargs) timeline.add(chart,month) return timeline
def plot_map(df): # maptype='china' 只显示全国直辖市和省级 # 数据只能是省名和直辖市的名称 # province_distribution = {'青岛': 22, '龙口': 37.56, '河北': 21, '辽宁': 12, '江西': 6, '上海': 20, '安徽': 10, '江苏': 16, '湖南': 9, '浙江': 13, '海南': 2, '广东': 22, '湖北': 8, '黑龙江': 11, '澳门': 1, '陕西': 11, '四川': 7, '内蒙古': 3, '重庆': 3, '云南': 6, '贵州': 2, '吉林': 3, '山西': 12, '山东': 11, '福建': 4, '青海': 1, '舵主科技,质量保证': 1, '天津': 1, '其他': 1} # provice=list(province_distribution.keys()) # values=list(province_distribution.values()) years = list(df.index) geos = [] timeline = Timeline(width=1700,height=900,is_auto_play=True, timeline_bottom=-10,timeline_symbol_size=20,timeline_play_interval=400,timeline_left=20,timeline_right=100 , \ is_timeline_show = False ) for index in range(len(years)): cities = list(df.columns) cities.remove('total') values = list(df.loc[years[index], :]) total_num = values[-1] del (values[-1]) # print(cities) # print(values) geos.append(Geo( str(int(total_num)), title_top="10%" , title_text_size=50 , subtitle = years[index] +" , subtitle", \ 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("title level1", 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 = {'赣江': [115.934192 , 28.826235] , '红河州' : [103.381549,23.369996] , '蒙自' : [103.371546,23.40208] , '海安' : [120.469259,32.544553] , \ '济阳' : [117.023094,36.965519] , '库车' : [82.970183,41.733785] , '文山-砚山' : [104.334442,23.621612] , '文安':[116.455985,38.891083] , '罗平':[104.309188,24.890519] , \ '宣城' : [118.762662,30.957007] , '古田' : [118.747401,26.596702] , '泗阳':[118.699691,33.723524] , } , \ pieces=[ {"min":0.1, "max": 50 , "label": "0-50"}, {"min": 51, "max": 100 , "label": "51-100"}, {"min": 101, "max": 200 , "label": "101-200"}, {"min":201, "max": 500, "label": "201-500"}, {"min":500, "max": 2900, "label": ">500"}, ] ) geos[index].show_config() geos[index].render("xxxx售出数量.html") # 时间轴定义 timeline.add(geos[index], years[index]) timeline.render('final_graph.html')
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 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 年')
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_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_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 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 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 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()
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()