def show_overview_day2(category, method, name): # if not _check_category(category): # return se = SE() m = getattr(se, method) _df1 = m() df1 = _df1[[ category, ]] _, df2 = get_line(indexs.get(category, '000001'), index=True) df1, df2 = reindex([df1, df2]) line1 = Line() if method in ('get_market_val', 'get_negotiable_val') \ and category in ('SZ', 'CYB', 'ZXQY'): line1.add(name, df1.index, df1[category] / 100000000, is_datazoom_show=False) else: line1.add(name, df1.index, df1[category], is_datazoom_show=False) line2 = Line() line2.add('index: %s' % indexs.get(category, '000001'), df2.index, df2.high, is_datazoom_show=True) overlap = Overlap() overlap.add(line1) # 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1 # 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变 overlap.add(line2, yaxis_index=1, is_add_yaxis=True) return overlap
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 loc_and_mean_age(info): grouped = group(info, ['cityChn']) tidy = grouped['age'] tidy_com = tidy.agg(['mean', 'count']) tidy_com.reset_index(inplace=True) tidy_com['mean'] = round(tidy_com['mean'], 2) attr = tidy_com['cityChn'] num = tidy_com['count'] aver = tidy_com['mean'] line = Line("小姐姐-平均年龄") line.add("年龄", attr, aver, is_stack=True, xaxis_rotate=30, mark_point=['max', 'min'], yaxis_min=26, is_splitline_show=False) bar = Bar("小姐姐-城区分布") bar.add("单位:人", attr, num, mark_point=['max'], mark_line=['average'], xaxis_rotate=30, yaxis_min=0) overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render("北京百合小姐姐平均年龄与分布.html")
def test_grid_add_overlap(): from pyecharts import Overlap grid = Grid() 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("Overlap+Grid 示例", width=1200, height=600, title_pos="40%") bar.add("蒸发量", attr, v1) bar.add( "降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250, legend_pos="85%", legend_orient="vertical", legend_top="45%", ) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_yaxis=True, yaxis_index=1) grid.add(overlap, grid_right="20%") grid.render()
def show_overview_day(category, method, name): # if not _check_category(category): index_data = services.line(indexs.get(category, '999999'), 'start', 'end', col='high') se_data = services.se(method[4:], category) df1 = pd.DataFrame.from_dict(index_data) df1.index = pd.DatetimeIndex(df1.index) df2 = pd.DataFrame.from_dict(se_data) df2.index = pd.DatetimeIndex(df2.index) df1, df2 = reindex2([df1, df2]) print(df1) print(df2) line1 = Line() line1.add(name, df2.index, df2[category.upper()], is_datazoom_show=False) line2 = Line() line2.add('index: %s' % indexs.get(category, '999999'), df1.index, df1['high'], is_datazoom_show=True) overlap = Overlap() overlap.add(line1) # 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1 # 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变 overlap.add(line2, yaxis_index=1, is_add_yaxis=True) return overlap
def view(numList): line = Line('折线图', width=2000) atter = ['数据异常', '不及格', '及格', '良好', '优秀', '满分'] v1 = [numList[0], numList[1], numList[2], numList[3], numList[4], numList[5]] line.add('最高成绩', atter, v1, mark_point=['max'], # 标点最大值 mark_line=['average']) # 虚线位置是平均分 line.add('最低成绩', atter, v1, mark_point=['min'], legend_pos='20%') es = EffectScatter() # 调用闪烁点 es.add('', atter, v1, effect_scale=8) # 调用合并函数,再一个图表上输出 overlop = Overlap() overlop.add(line) overlop.add(es) pie = Pie('饼图', title_pos='80%') pie.add('', atter, v1, radius=[60, 30], # 控制内外半径的 center=[65, 50], legend_pos='80%', legend_orient='vertical') # 显示两个示例图的调用函数,不然会覆盖 grid = Grid() grid.add(overlop, grid_right='50%') grid.add(pie, grid_left='60%') grid.render('abc.html')
def drawfunc(self, A, text, yaxis_max=200000, yaxis_force_interval=0.25, width=1000): '''坏账率绘图函数''' bar = Bar(text, title_pos='center', width='100%') line = Line(text, title_pos='center', width='100%') bar.add("好客户", A.iloc[:, 0].tolist(), A['好客户'].tolist(), yaxis_min=0, yaxis_max=yaxis_max, is_label_show=True, label_pos='inside', label_color=['#FFB6B9'], legend_pos='right', legend_orient='vertical', is_stack=True) bar.add("坏客户", A.iloc[:, 0].tolist(), A['坏账'].tolist(), yaxis_min=0, yaxis_max=yaxis_max, is_label_show=True, label_pos='inside', label_color=['#BBDED6'], legend_pos='right', legend_orient='vertical', is_stack=True) line.add('坏账率', A.iloc[:, 0].tolist(), A['坏账率'].tolist(), yaxis_min=0, yaxis_max=1, yaxis_force_interval=yaxis_force_interval, is_smooth=True, legend_pos='right', point_symbol='circle', legend_orient='vertical', line_width=2, is_label_show=True) line.add('总体坏账率', A.iloc[:, 0].tolist(), A['总体坏账率'].tolist(), yaxis_min=0, yaxis_max=1, yaxis_force_interval=yaxis_force_interval, is_smooth=True, legend_pos='right', legend_orient='vertical', line_width=2, line_type='dotted') overlap = Overlap(width='100%') overlap.add(bar) overlap.add(line, is_add_yaxis=True, yaxis_index=1) grid = Grid(width=width) grid.add(overlap, grid_right='10%') return grid
def form_valid(self, form): line1 = Line() val1 = services.line(form.cleaned_data['code1'], form.cleaned_data['start'], form.cleaned_data['end'], form.cleaned_data['col1'], form.cleaned_data['is_index1']) line1.add(services.code_str(form.cleaned_data['code1']), list(val1.keys()), list(val1.values())) line2 = Line() val2 = services.line(form.cleaned_data['code2'], form.cleaned_data['start'], form.cleaned_data['end'], form.cleaned_data['col2'], form.cleaned_data['is_index2']) line2.add(services.code_str(form.cleaned_data['code2']), list(val2.keys()), list(val2.values())) overlap = Overlap( '%s-%s' % (form.cleaned_data['start'], form.cleaned_data['end'])) overlap.add(line1) overlap.add(line2, yaxis_index=1, is_add_yaxis=True) return show(self.request, overlap)
def get_chatrs(train, col): data = train.groupby([col])['Attrition'] data_sum = data.sum() # 离职人数 data_mean = data.mean() # 离职率 bar = Bar(col, title_pos="45%") bar.add('离职人数', data_sum.index, data_sum.values, mark_point=['max'], yaxis_formatter='人', yaxis_max=200, legend_pos="40%", legend_orient="vertical", legend_top="95%", bar_category_gap='25%') line = Line() line.add('离职率', data_mean.index, data_mean.values, mark_point=['max'], mark_line=['average'], yaxis_max=0.8) overlap = Overlap(width=900, height=400) overlap.add(bar) overlap.add(line, is_add_yaxis=True, yaxis_index=1) return overlap
def name_trend(name, data, gender=['M','F'], year=1920, dodge = 500): if isinstance(gender, str): name_data = data[(data['Name'] == name)&(data['Gender']==gender)&(data['Year']>=year)] attr = list(name_data['Year'].values) attr1=list(map(str,attr)) bar = Bar("名人名字的影响",width=1000, height=600) bar.add(name, attr, list(name_data['Count'].values), mark_line=["average"], mark_point=["max", "min"], legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) line = Line() line.add(name, attr1, list(name_data['Count'].values + dodge)) else: name_data = data[(data['Name'] == name)&(data['Year']>=year)] attr = list(range(year, 2018)) attr1=list(map(str,attr)) v1 = name_data[name_data['Gender']==gender[0]].Count.values v2 = name_data[name_data['Gender']==gender[1]].Count.values bar = Bar("名人名字的影响",width=1000, height=600) bar.add(name+"男", attr, list(v1), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) bar.add(name+"女", attr, list(v2), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) line = Line() line.add(name+"男", attr1, list(v1 + dodge)) line.add(name+"女", attr1, list(v2 + dodge)) overlap = Overlap() overlap.add(bar) overlap.add(line) page.add(overlap)
def forecastPlot(foreData, target, localPath): """ :param ismn_data: DataFrame. Merged dataset of ISMN :return: html file stored in paht './plot/ismn_ts' """ # create a new folder: plot/ismn_ts path = '../{}/predictionPlot'.format(localPath) if not os.path.exists(path): os.makedirs(path) foreData = foreData.copy() foreData['timeStamp'] = pd.to_datetime(foreData['timeStamp']) for station in foreData.station.unique(): line = Line("forecast of soil mosture at %i cm" % target, station) overlap = Overlap(width=1200, height=500) dataset = foreData[foreData.station == station] dataset.index = dataset.timeStamp fore_columns = list(dataset.filter(regex='fore|actual').columns) for forecastVar in fore_columns: x = dataset.index y = list(dataset.loc[:, [forecastVar]].values.reshape(-1)) line.add(forecastVar, x, y, is_datazoom_show=True) overlap.add(line) overlap.render(path=path + '/{0}_forecast_{1}cm.html'.format(station, target))
def avg(): df = pd.read_csv('maoyan2.csv', error_bad_lines=False) df.round(2) # 根据日期统计各天的平均值,并保留两位小数 date_score_avg = df.groupby('date')['score'].mean().round(2)*2 # 根据评分数据生成柱状图 bar = Bar('评分走势图', '数据来源:不正经程序员-采集自猫眼', title_pos='center', width=1500, height=600) # line = Line() # line.add('', attr, value) bar.add('', date_score_avg.index, date_score_avg.values, is_visualmap=False, visual_range=[0, 3500], visual_text_color='#fff', is_more_utils=True, is_label_show=True, xaxis_interval=0, xaxis_rotate=30, mark_line=["average"]) overlap = Overlap() overlap.add(bar) # overlap.add(line) overlap.show_config() overlap.render( 'picture\评分走势图.html') # 根据日期统计各天的平均值,并保留两位小数 date_positive_prob_avg = df.groupby('date')['positive_prob'].mean().round(2) bar = Bar('评论情感指数走势图', '数据来源:不正经程序员-采集自猫眼', title_pos='center', width=1500, height=600) # line = Line() # line.add('', attr, value) bar.add('', date_positive_prob_avg.index, date_positive_prob_avg.values, is_visualmap=False, visual_range=[0, 3500], visual_text_color='#fff', is_more_utils=True, is_label_show=True, xaxis_interval=0, xaxis_rotate=30, mark_line=["average"]) overlap = Overlap() overlap.add(bar) # overlap.add(line) overlap.show_config() overlap.render( 'picture\评论情感指数走势图.html')
def na_timeline(dff,column,time_col,time_type=None): # time_col should be format like 'yyyy-mm-dd', such as '2018-01-17' df = dff.copy() df['na']=df[df[column].columns.values.tolist()].T.count() df['na'] = df['na'].map(lambda x: 1 if x>0 else np.nan) if time_type == 'timestamp': df[time_col] = df[time_col].map(lambda x: datetime.datetime.fromtimestamp(x).strftime("%Y-%m-%d")) elif time_type == 'time_str': df[time_col] = df[time_col].map(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")) else: df[time_col] = df[time_col].map(lambda x: x.strftime("%Y-%m-%d")) attr = df[[time_col]+column].groupby(time_col).size().index.tolist() v1 = df[[time_col]+column+['na']].groupby(time_col).size().values.tolist() v2 = (np.round(100-df[[time_col]+['na']].groupby(time_col).count()['na'].values.tolist()/df[[time_col]+column+['na']].groupby(time_col).size()*100)).values.tolist() bar = Bar(width=1200, height=600,title='NA Timeline') bar.add("数量", attr, v1,is_stack=True,is_datazoom_show=True,datazoom_type='both',datazoom_range=[0,100], label_color=['#0081FF','#FF007C'],is_visualmap=True, visual_type='size',visual_range=[0,100], visual_range_size=[10,10],is_yaxislabel_align=False,visual_dimension=1,tooltip_text_color='#000000', label_emphasis_textcolor='#000000',is_more_utils=True) line = Line() line.add('缺失率', attr, v2, yaxis_formatter="%", yaxis_min=0,yaxis_max=100,label_emphasis_textcolor='#000000', mark_line=['average'],line_width=3) overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) return overlap
def MACD(self): dif, dea, macd = self.__macd() overlap = Overlap() macdBar = Bar() macdBar.add("", self.__date, macd, is_datazoom_show=True, is_visualmap=True, is_piecewise=True, pieces=[ { 'min': 0, 'max': 300, 'color': "#f47920" }, { 'min': -300, 'max': 0, 'color': "#f6f5ec" }, ]) macdline = Line() macdline.add("", self.__date, dif, is_smooth=False) macdline.add("", self.__date, dea, is_smooth=False) overlap.add(macdBar) overlap.add(macdline) return overlap
def plot_days_to_trend(video_df, save_filename): """ 使用 pyecharts 统计视频发布后上榜的天数 :param - video_df: - save_filename: """ video_df['diff'] = (video_df['trending_date'] - video_df['publish_time']).dt.days days_df = video_df['diff'].value_counts() # 观察视频发布后2个月的情况 days_df = days_df[(days_df.index >= 0) & (days_df.index <= 60)] days_df = days_df.sort_index() bar = Bar('视频发布后2个月的情况') bar.add( '柱状图', days_df.index.tolist(), days_df.values.tolist(), is_datazoom_show=True, # 启用数据缩放功能 datazoom_range=[0, 50] # 百分比范围 ) line = Line() line.add('折线图', days_df.index.tolist(), days_df.values.tolist()) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render(os.path.join(config.output_path, save_filename))
def kline_plot(self,ktype=0): df=self.cal_hadata() #画K线图数据 date = df.index.strftime('%Y%m%d').tolist() if ktype==0: k_value = df[['open','close', 'low','high']].values else: k_value = df[['ha_open','ha_close', 'ha_low', 'ha_high']].values #引入pyecharts画图使用的是0.5.11版本,新版命令需要重写 kline = Kline(self.name+'行情走势') kline.add('日K线图', date, k_value, is_datazoom_show=True,is_splitline_show=False) #加入5、20日均线 df['ma20']=df.close.rolling(20).mean() df['ma5']=df.close.rolling(5).mean() line = Line() v0=df['ma5'].round(2).tolist() v=df['ma20'].round(2).tolist() line.add('5日均线', date,v0, is_symbol_show=False,line_width=2) line.add('20日均线', date,v, is_symbol_show=False,line_width=2) #成交量 bar = Bar() bar.add('成交量', date, df['vol'],tooltip_tragger='axis', is_legend_show=False, is_yaxis_show=False, yaxis_max=5*max(df['vol'])) overlap = Overlap() overlap.add(kline) overlap.add(line,) overlap.add(bar,yaxis_index=1, is_add_yaxis=True) return overlap
def xuqiu_diqu_mon(conn, width, height, mon): sql_xuqiu_diqu = "select name,count,mj from kanban_xuqiu_diqu where year(date_sub(create_date,interval 1 month))='%s'" \ "and month(date_sub(create_date,interval 1 month))='%s' order by mj desc"%(str(mon)[:4],str(mon)[-2:]) data_xuqiu_diqu = pd.read_sql(sql_xuqiu_diqu, conn) xuqiu_diqu_name = list(data_xuqiu_diqu.iloc[:, 0]) xuqiu_diqu_mj = list(data_xuqiu_diqu.iloc[:, 2]) xuqiu_diqu_count = list(data_xuqiu_diqu.iloc[:, 1]) xuqiu_diqu_title = str(mon)[:4] + '年' + str(mon)[-2:] + '月土流网土地需求区域分布' xuqiu_diqu_bar = Bar(xuqiu_diqu_title) xuqiu_diqu_bar.add("面积(亩)", xuqiu_diqu_name, xuqiu_diqu_mj, xaxis_interval=0, xaxis_rotate=90) xuqiu_diqu_line = Line() xuqiu_diqu_line.add("宗数", xuqiu_diqu_name, xuqiu_diqu_count, xaxis_interval=0, xaxis_rotate=90) xuqiu_diqu_overlap = Overlap(height=height, width=width) xuqiu_diqu_overlap.add(xuqiu_diqu_bar) xuqiu_diqu_overlap.add(xuqiu_diqu_line, yaxis_index=1, is_add_yaxis=True) xuqiu_diqu_overlap.render() return xuqiu_diqu_overlap
def assets_curve(dates, sum): xs = dates ys = sum xs_date = [x.date() for x in xs] line = Line("盈利走势图") line.add("盈利", xs_date, sum, is_smooth=True, mark_line=["min", "max", "average"], mark_point=[ 'min', 'max', 'average', { "coord": [xs_date[-1], ys[-1]], "name": "now" } ], is_datazoom_show=True, xaxis_name="时间", yaxis_name="元", tooltip_trigger="axis") overlap = Overlap(width=1200, height=600) # 默认不新增 x y 轴,并且 x y 轴的索引都为 0 overlap.add(line) overlap.render('profit.html')
def brush(data): data = hist_sum(data) kline = Kline() kline.add( 'Kline', data.index, data.loc[:, ['open', 'close', 'low', 'high']].values, mark_line=['max', 'min'], mark_line_valuedim=['highest', 'lowest'], is_datazoom_show=True, datazoom_xaxis_index=[0, 1], ) brush = Line() brush.add( 'Brush', data.index, data.endpoint.values, ) overlap = Overlap() overlap.add(kline) overlap.add(brush) macd = Bar() macd.add( 'MACD', data.index, data.hist_sum.values, ) page = Page() page.add(overlap) page.add(macd) return page
def generate_score_tabale(): city_main = city_com.sort_values('count', ascending=False)[0:20] attr = city_main['city'] v1 = city_main['count'] v2 = city_main['mean'] line = Line("主要城市平均评分") line.add("主要城市平均评分", attr, v2, is_stack=True, xaxis_rotate=50, yaxis_min=4.0, mark_point=['min', 'max'], xaxis_interval=0, line_color='lightblue', line_width=4, mark_point_textcolor='yellow', mark_point_color='lightblue', is_splitline_show=False) bar = Bar("主要城市评论数及评分") bar.add("主要城市评论数", attr, v1, is_stack=True, xaxis_rotate=50, yaxis_min=0, xaxis_interval=0, is_splitline_show=False) overlap = Overlap() # 默认不新增 x y 轴,并且 x y 轴的索引都为 0 overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render('resources/city_score.html')
def strategy(): form = request.form getStock = form.get('stock') stock = getStock if getStock else "usTSLA" getCircle = form.get('circle') circle = getCircle if getCircle else "120" buyStrategy = BuyTrendStrategy(stock, int(circle), 1000000) closeDayList, closeValueList = buyStrategy.get_close_line() buyDayList, buyValueList = buyStrategy.get_buy_point() closeLine = Line("趋势购买策略", width="400", height="300") closeLine.add(stock, closeDayList, closeValueList) buyES = EffectScatter("购买点", width="400", height="300") buyES.add("购买点", buyDayList, buyValueList, symbol_size=8, effect_scale=3, effect_period=3, symbol="triangle") overlap = Overlap() overlap.add(closeLine) overlap.add(buyES) return render_template( "strategy.html", strategyEchart=overlap.render_embed(), host=REMOTE_HOST, script_list=buyES.get_js_dependencies(), )
class PlotBarWithLine: def __init__(self): self.data = {{'label': []}, } self.titles = '' self.indexes = [] self.bar = Bar() self.line = Line() self.overlap = Overlap() self.script_list = self.overlap.get_js_dependencies() def plot_bar_line(self, dat, tit, ind): self.data = dat self.titles = tit self.indexes = ind self.bar = Bar(self.titles) for label in self.data.keys(): label_bar = '{}_B'.format(label) label_line = '{}_L'.format(label) self.bar.add(label_bar, self.indexes, self.data[label], is_label_show=True) self.line.add(label_line, self.indexes, self.data[label], is_label_show=True, mark_point=['max', 'min']) self.overlap.add(self.bar) self.overlap.add(self.line) return self.overlap.render_embed()
def missing_check(df,columns,miss_rate=0.8,handling=None): temp = pd.DataFrame(df[columns].isnull().sum()) temp = temp.reset_index().rename(columns={'index':'feature',0:'missing'}) temp = temp.sort_values('missing',ascending=True) temp['missing_rate'] = np.round(temp['missing']/df.shape[0],2)*100 temp = temp[temp['missing_rate']>miss_rate] attr = temp.feature.values.tolist() v1 = temp.missing.values.tolist() v2 = temp.missing_rate.values.tolist() bar = Bar() bar.add('缺失量',attr,v1,is_stack=True,is_datazoom_show=True,datazoom_type='both',datazoom_range=[0,100], label_color=['#0081FF','#FF007C'],is_visualmap=True, visual_type='size',visual_range=[0,100], visual_range_size=[10,10],is_yaxislabel_align=False,visual_dimension=1,tooltip_text_color='#000000', label_emphasis_textcolor='#000000',is_more_utils=True,yaxis_rotate=45,label_emphasis_pos='right', is_convert=True) line=Line() line.add('缺失率', attr, v2, yaxis_formatter="%", yaxis_min=0,yaxis_max=100,label_emphasis_textcolor='#000000',line_width=3, label_emphasis_pos='right',is_convert=True) overlap = Overlap(width=1000,height =np.round(temp.shape[0]/2)*30) overlap.add(bar) overlap.add(line, xaxis_index=1, is_add_xaxis=True) if handling == None: return overlap elif handling == 'drop': return temp['feature'].values.tolist()
def test_grid_add_overlap(): from pyecharts import Overlap grid = Grid() 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("Overlap+Grid 示例", width=1200, height=600, title_pos="40%") bar.add("蒸发量", attr, v1) bar.add( "降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250, legend_pos="85%", legend_orient="vertical", legend_top="45%", ) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_yaxis=True, yaxis_index=1) grid.add(overlap, grid_right="20%") grid.render()
def moneyflow_lgt(date_start, date_end, df, save_path_moneyflow_lgt): df = df.assign(hgt=df.hgt.apply(lambda x: round(x / 100, 2))) df = df.assign(sgt=df.sgt.apply(lambda x: round(x / 100, 2))) df = df.assign( north_money=df.north_money.apply(lambda x: round(x / 100, 2))) title = ' 资金流向 - 陆股通(亿元)' subtitle = ' GZH: 摸鱼大佬' bar = Bar(title, subtitle, title_pos=0.1, subtitle_text_size=15, subtitle_color='#aa8') # bar.use_theme("macarons") bar.add("沪股通", df['trade_date'], df['hgt'], bar_category_gap='40%') bar.add("深股通", df['trade_date'], df['sgt'], bar_category_gap='40%') line = Line() line.add("北上资金", df['trade_date'], df['north_money'], mark_line=['average'], mark_point=['min', 'max']) overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_xaxis=False) #是否新增一个 x 坐标轴,默认为 False render_path = save_path + 'moneyflow_lgt_' + date_end + '.png' # bar.render(path=render_path) overlap.render(path=render_path) # pic_zoom(render_path, save_path_tgbhotstock, 740) print('moneyflow_lgt done: ' + render_path) return render_path
def name_trend(name, data, gender=['M','F'], year=1920, dodge = 500): if isinstance(gender, str): name_data = data[(data['Name'] == name)&(data['Gender']==gender)&(data['Year']>=year)] attr = list(name_data['Year'].values) bar = Bar(name) bar.add("", attr, list(name_data['Count'].values), mark_line=["average"], mark_point=["max", "min"], legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) line = Line() line.add("", attr, list(name_data['Count'].values + dodge)) else: name_data = data[(data['Name'] == name)&(data['Year']>=year)] attr = list(range(year, 2018)) v1 = name_data[name_data['Gender']==gender[0]].Count.values v2 = name_data[name_data['Gender']==gender[1]].Count.values bar = Bar(name) bar.add("男", attr, list(v1), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) bar.add("女", attr, list(v2), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) line = Line() line.add("", attr, list(v1 + dodge)) line.add("", attr, list(v2 + dodge)) overlap = Overlap() overlap.add(bar) overlap.add(line) return overlap.render(str(name)+str(gender)+str(dodge)+'.html')
def example1(time_list, base_list, net_list, close_list): overlap = Overlap( width=1600, height=800, ) line = Line() line.add( "BTC基准线", time_list, base_list, is_datazoom_show=True, is_datazoom_extra_show=True, is_legend_show=True, # is_label_show=True, is_more_utils=True, is_xaxislabel_align=True, is_yaxislabel_align=True, line_color="#7CFC00", line_width=3, tooltip_axispointer_type="cross", # mark_point=["max", "min"] ) line.add( "净值", time_list, net_list, is_datazoom_show=True, is_datazoom_extra_show=True, is_legend_show=True, # is_label_show=True, is_more_utils=True, is_xaxislabel_align=True, is_yaxislabel_align=True, line_color="#00ff00", line_width=5, tooltip_axispointer_type="cross", # mark_point=["max", "min"] ) line2 = Line() line2.add( "BTC价格", time_list, close_list, is_datazoom_show=True, is_datazoom_extra_show=True, is_legend_show=True, # is_label_show=True, is_more_utils=True, is_xaxislabel_align=True, is_yaxislabel_align=True, line_color="#696969", line_width=3, # mark_point=["max", "min"] ) overlap.add(line) overlap.add(line2, is_add_yaxis=True, yaxis_index=1) overlap.render()
def show_charts(error_data, last_time): charts_data = error_data.copy() charts_data.pop("null_name") codes = [v[0] for k, v in charts_data.items() if len(v) != 0] print(codes) if len(codes) > 0: page = Page() limit = minutes.index(last_time) + 1 mins = [str(x)[:-2] + ":" + str(x)[-2:] for x in minutes[:limit]] for code in codes: print(code) pipeline4 = [{ "$unwind": "$data" }, { "$match": { "_id": code } }, { "$limit": limit }] stks_data = table.aggregate(pipeline4) price = [] avg_px = [] chg_pct = [] for stk in stks_data: price.append(round(stk["data"]["current_px"], 2)) avg_px.append(round(stk["data"]["avg_px"], 2)) chg_pct.append(stk["data"]["chg_pct"]) last_value = min(price + avg_px) line = Line(code) line.add("cur_price", mins, price, yaxis_min=last_value, tooltip_axispointer_type='cross', is_smooth=True) line.add("avg_price", mins, avg_px, yaxis_min=last_value, tooltip_axispointer_type='cross', is_smooth=True) line1 = Line() line1.add("chg_pct", mins, chg_pct, tooltip_axispointer_type='cross', is_smooth=True, yaxis_formatter="%") overlap = Overlap() overlap.add(line) overlap.add(line1, yaxis_index=1, is_add_yaxis=True) page.add(line) page.render(u"html\\" + str(last_time) + ".html")
def overlap_container(): overlap = Overlap(page_title="Overlap Container") stack_bar, line = StackBar.stack_bar() overlap.add(stack_bar) overlap.add(line) return overlap
def view(code, start_, end_, days): ''' 使用pyecharts展示数据 :param code: 股票代码 :param start_: 开始时间(包含)格式为'2018-01-01' :param end_: 结束时间(包含)格式为'2018-01-01' :param days: 设置求多少天内波动率 :return: ''' th = get_data_from_db(code, start_, end_) # 中间有数据缺失的情况,因为股票在工作日才会交易,非工作日的交易数据是缺失的,我们要填充上去 l = len(th) start = th.iloc[0:1].index.tolist()[0] end = th.iloc[l - 1:l].index.tolist()[0] idx = pd.date_range(start=start, end=end) # 接着我们使用reindex函数将缺失数据补全 # 数据补全的规则是,价格数据用前一个交易日的数据来填充,但是交易量需要填充为0 data = th.reindex(idx) zvalues = data.loc[~(data.volume > 0)].loc[:, ['volume']] data.update(zvalues.fillna(0)) # pad/ffill:用前一个非缺失值去填充该缺失值 # backfill/bfill:用下一个非缺失值填充该缺失值 data.fillna(method='ffill', inplace=True) # # 根据分组索引来分组,days为分组时间长度 group_index = gen_item_group_index(len(data), days) data['group_index'] = group_index group = data.groupby('group_index').agg({ 'volume': 'sum', 'low': 'min', 'high': _high_price }) # 添加每个分组起始日期 data_col = pd.DataFrame({'group_index': group_index, 'date': idx}) group['date'] = data_col.groupby('group_index').agg('first') # 添加波动率 group['ripples_radio'] = group.high / group.low attr = [str(x.strftime('%Y-%m-%d')) for x in group.date] v1 = [round(x, 2) for x in group.ripples_radio.tolist()] v2 = [round(x / 10000, 2) for x in group.volume.tolist()] bar = Bar(width=1200, height=600) bar.add("波动率", attr, v1) line = Line() line.add("成交量", attr, v2, yaxis_formatter=" 万手") overlap = Overlap() # 默认不新增 x y 轴,并且 x y 轴的索引都为 0 overlap.add(bar) # 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1 # 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变 overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render('股票[{0}]{1}天波动率和成交量图.html'.format(code, days))
def combinate(base, other, xIndex=0, yIndex=0, addX=False, addY=False): nt = Overlap() nt.add(base) nt.add(other, xaxis_index=xIndex, yaxis_index=yIndex, is_add_xaxis=addX, is_add_yaxis=addY) return nt
def test_line_es(): v1 = [5, 20, 36, 10, 10, 100] line = Line("line-EffectScatter 示例") line.add("", CLOTHES, v1, is_random=True) es = EffectScatter() es.add("", CLOTHES, v1, effect_scale=8) overlap = Overlap() overlap.add(line) overlap.add(es) overlap.render()
def test_overlap_bar_line(): attr = ["A", "B", "C", "D", "E", "F"] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line-Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
def test_overlap_bar_line(): attr = ['A', 'B', 'C', 'D', 'E', 'F'] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line-Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
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 test_overlap_kline_line(): import random v1 = [ [2320.26, 2320.26, 2287.3, 2362.94], [2300, 2291.3, 2288.26, 2308.38], [2295.35, 2346.5, 2295.35, 2345.92], [2347.22, 2358.98, 2337.35, 2363.8], [2360.75, 2382.48, 2347.89, 2383.76], [2383.43, 2385.42, 2371.23, 2391.82], [2377.41, 2419.02, 2369.57, 2421.15], [2425.92, 2428.15, 2417.58, 2440.38], [2411, 2433.13, 2403.3, 2437.42], [2432.68, 2334.48, 2427.7, 2441.73], [2430.69, 2418.53, 2394.22, 2433.89], [2416.62, 2432.4, 2414.4, 2443.03], [2441.91, 2421.56, 2418.43, 2444.8], [2420.26, 2382.91, 2373.53, 2427.07], [2383.49, 2397.18, 2370.61, 2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] attr = ["2017/7/{}".format(i + 1) for i in range(31)] kline = Kline("Kline-Line 示例") kline.add("日K", attr, v1) line_1 = Line() line_1.add("line-1", attr, [random.randint(2400, 2500) for _ in range(31)]) line_2 = Line() line_2.add("line-2", attr, [random.randint(2400, 2500) for _ in range(31)]) overlap = Overlap() overlap.add(kline) overlap.add(line_1) overlap.add(line_2) overlap.render()
def test_overlap_two_yaxis(): 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(width=1200, height=600) 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) overlap.render()
def test_overlap_es_scatter(): v1 = [10, 20, 30, 40, 50, 60] v2 = [30, 30, 30, 30, 30, 30] v3 = [50, 50, 50, 50, 50, 50] v4 = [10, 10, 10, 10, 10, 10] es = EffectScatter("Scatter-EffectScatter 示例") es.add("es", v1, v2) scatter = Scatter() scatter.add("scatter", v1, v3) es_1 = EffectScatter() es_1.add("es_1", v1, v4, symbol='pin', effect_scale=5) overlap = Overlap() overlap.add(es) overlap.add(scatter) overlap.add(es_1) overlap.render()
quantity = [] for i in sorted(genres.items(), key=lambda item:sum(item[1]['boxoffice_num']), reverse=True): styles.append(i[0]) boxoffice.append(round(sum(genres[i[0]]['boxoffice_num']), 2)) avg_boxoffice.append(round(np.mean(genres[i[0]]['boxoffice_num']), 2)) quantity.append(len(genres[i[0]]['boxoffice_num'])) grid = Grid() bar1 = Bar(title='类型-票房') # ,title_pos='40%' bar2 = Bar() bar1.add('总票房',styles, boxoffice, xaxis_name='类型', yaxis_name='总票房(亿)', yaxis_name_gap=40, is_toolbox_show=False) bar2.add('平均票房', styles, avg_boxoffice, xaxis_name='类型', yaxis_name='平均票房(亿)', is_toolbox_show=False) overlap = Overlap(width=1200, height=600) overlap.add(bar1) overlap.add(bar2, is_add_yaxis=True, yaxis_index=1) grid.add(overlap, grid_right="20%") grid#.render('类型-票房.html') # 上图为2018年不同类型电影的总票房和平均票房。由于一部电影一般会有多个类型,因此在计算票房时,分别考虑了该电影的每个类型。以‘红海行动’为例,‘红海行动’为动作片、战争片,因此在动作片和战争片中,都分别考虑了‘红海行动’的票房。 # # 可以看出,就总票房而言,动作片总票房最高,喜剧片紧随其后。而就平均票房而言,科幻和战争片的平均票房较高,这可能是由于这些类型的电影制作用了更大的成本,制作较好,因此也回收了更多的票房。 # In[16]: genres = {} other_list = ['武侠', '悬疑', '儿童', '历史', '家庭', '古装', '传记', '纪录片', '音乐', '歌舞', '恐怖', '灾难', '运动', '同性', '西部', '戏曲']
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()
# In[239]: from pyecharts import Bar, Line, Overlap, Grid years = [str(i) for i in range(2008, 2018)] net_sales = data.loc['净销售额'].values net_income = data.loc['净利润'].values bar = Bar("盈利能力") bar.add("净销售额", years, net_sales) bar.add("净利润", years, net_income, bar_category_gap=25, yaxis_name='百万美元', yaxis_name_gap=60) gross = data.loc['毛利率'].values line = Line() line.add("毛利率", years, gross, line_width=3) ol = Overlap() ol.add(bar) ol.add(line, is_add_yaxis=True, yaxis_index=1) ol # In[241]: assets = data.loc['总资产'].values cash = data.loc['现金'].values bar = Bar("财务状况") bar.add("总资产", years, assets) bar.add("现金", years, cash, bar_category_gap=25, yaxis_name='百万美元', yaxis_name_gap=60) bar
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()
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()
import numpy as np arr = np.array(data) # In[57]: from pyecharts import Bar, Line, Overlap bar = Bar("历年报考人数与录取率") bar.add("报考人数",arr[::-1,0] , arr[::-1,1]) bar.add("录取人数",arr[::-1,0] , arr[::-1,2]) line = Line() line.add("录取率",arr[::-1,0] , arr[::-1,3]*10, line_width=3, line_color='green') ol = Overlap() ol.add(bar) ol.add(line) ol # In[112]: data_born = [[124761, 123626, 122389, 121121, 119850, 118517, 117171, 115823, 114333, 112704, 111026, 109300, 107507, 105851, 104357, 103008, 101654, 100072, 98705, 97542, 96259, 94974, 93717, 92420, 90859, 89211, 87177, 85229, 82992, 80671, 78534, 76368, 74542, 72538, 70499, 69172, 67296, 65859, 66207, 67207, 65994], [14.64, 15.64, 16.57, 16.98, 17.12, 17.70, 18.09, 18.24, 19.68, 21.06, 21.58, 22.37, 23.33, 22.43, 21.04, 19.90, 20.19, 22.28, 20.91, 18.21, 17.82, 18.25, 19.03, 20.01, 23.13, 24.95, 28.07, 29.92, 30.74, 33.59, 34.25, 35.75, 34.12, 35.21, 38.00, 39.34, 43.60, 37.22, 18.13, 20.86, 24.78]] arr_born = np.array(data_born) list_born = list((arr_born[0]*arr_born[1]/1000)[::-1]) list_born # In[113]: