def gzu_major_satisfied(): data1 = analysis_data.gzu_satisfied() data1 = data1.iloc[:, :5] print(data1) type_sas = { '综合满意度': 'all', '办学条件满意度': 'facility', '教学质量满意度': 'teaching', '就业满意度': 'job' } c = Bar() for a in type_sas: c.add_xaxis([str(x) for x in data1['major'].values]) c.add_yaxis(a, [x for x in data1[type_sas[a]].values]) c.set_global_opts( yaxis_opts=opts.AxisOpts(min_=3), xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(font_size=10, interval=0)), datazoom_opts=opts.DataZoomOpts()) c.set_series_opts( label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), ]), markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="average", name="平均值"), ]), ) return c
def plt_feat_import(model_name, max_cols=9999, max_print=10): from pyecharts.globals import CurrentConfig, NotebookType CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB from pyecharts import options as opts from pyecharts.charts import Bar # 处理数据并排序 x_name = model_name.feature_name() y_val = [int(x) for x in model_name.feature_importance()] val_pairs = [x for x in zip(x_name, y_val)] val_pairs.sort(key=lambda x: x[1]) # 设置图像属性 bar = Bar() bar.add_xaxis([x[0] for x in val_pairs][-max_cols:]) bar.add_yaxis("特征重要度", [x[1] for x in val_pairs][-max_cols:]) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=True, position='right')) bar.set_global_opts( title_opts=opts.TitleOpts(title="特征重要度"), datazoom_opts=opts.DataZoomOpts(), ) bar.reversal_axis() print(val_pairs[-max_print:][::-1]) return bar
def coincedence(place) -> Bar: place = np.array(place) foo = place[:, 1].astype(np.float) order = np.argsort(foo) k = 0 place1 = np.copy(place) for i in order: place1[k] = place[i, :] k = k + 1 place = place1 bar = Bar() bar.add_xaxis(list(place[:, 0])) bar.add_yaxis("热度", list(place[:, 1])) bar.set_global_opts(title_opts=opts.TitleOpts(title="外来旅游人口相关度")) bar.set_global_opts(xaxis_opts=opts.AxisOpts(boundary_gap=1, interval=0, axislabel_opts={"rotate": 45}), toolbox_opts=opts.ToolboxOpts(is_show=True), datazoom_opts=[ opts.DataZoomOpts(range_start=0, range_end=100, is_zoom_lock=False) ]) #bar.set_global_opts(xaxis_opts=opts.AxisTickOpts(is_align_with_label=0)) bar.set_series_opts(label_opts=opts.LabelOpts(font_size=9)) bar.width = 1200 bar.render(path="外来旅游人口相关度.html") return True
def draw_balance_bar(xaxis, yaxis, title="消费统计", markline=None, width=2000) -> Bar: """ x = [月_日, 月_日, 月_日, ....] y = [(title1, [num1, num2, num3, num4, ...]), (title2, [num1, num2, num3, num4, ...])] :param xaxis: x轴 :param yaxis: y轴 :param title: 标题 :param markline: 标记辅助线 :param width: 宽 :return: Bar """ bar = Bar() bar.add_xaxis(xaxis) for name, axis in yaxis: bar.add_yaxis(name, axis, category_gap="20%", gap="0%") bar.set_global_opts(title_opts=opts.TitleOpts(title=title, ), datazoom_opts=[opts.DataZoomOpts(range_start=0, range_end=100), opts.DataZoomOpts(type_="inside")], tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='shadow')) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) if markline is not None: bar.set_series_opts(markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem( y=markline, name='预算') ]) ) return bar
def paint_bar(self, x: list, collects: list, title: str, mark_point: bool = False): bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)) bar.add_xaxis(x) for collect in collects: for i, (name, unit, data) in enumerate(collect): bar.add_yaxis(f'{name}-单位:{unit}', data, yaxis_index=i) if i != 0: bar.extend_axis(yaxis=opts.AxisOpts( name='', type_='value', position='right', )) bar.set_global_opts(title_opts=opts.TitleOpts(title=title, pos_left='5%'), legend_opts=opts.LegendOpts(pos_bottom='0')) bar.set_series_opts( label_opts=opts.LabelOpts(position='top'), tooltip_opts=opts.TooltipOpts(formatter=f'{{b}}年{{a}}:{{c}}')) if mark_point: bar.set_series_opts( markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_='max', name='最大值'), opts.MarkPointItem(type_='min', name='最小值') ], symbol_size=80)) return bar
def bar(x, y): bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS)) bar.add_xaxis(x) bar.add_yaxis("盈利", y) bar.set_global_opts(title_opts=opts.TitleOpts(title="380平台月盈利")) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) bar.render('../graph/4.1平台月盈利.html')
def bar(self,df,legend,title,path): ''' 柱状图 :param df: 要操作的数据 :param legend: 图例 :param title: 报表标题 :param path: 保存路径 :return: ''' tmp = df.value_counts() x = list(tmp.index) y = list(tmp) bar = Bar() bar.add_xaxis(x) bar.add_yaxis(legend, y, category_gap="60%") bar.set_series_opts(itemstyle_opts={ "normal": { "color": utils.JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: 'rgba(0, 244, 255, 1)' }, { offset: 1, color: 'rgba(0, 77, 167, 1)' }], false)"""), "barBorderRadius": [30, 30, 30, 30], "shadowColor": 'rgb(0, 160, 221)', }}) bar.set_global_opts(title_opts=opts.TitleOpts(title=title)) bar.render(path + '/' + title + '.html')
def generte_bar_chart(title: str, xaxis_caption: str, range_groups: List[IntegerRangeCounterGroup], bar_gap: int = 4) -> Bar: chart = Bar() chart.set_global_opts( title_opts=opts.TitleOpts(title=title), yaxis_opts=opts.AxisOpts( name='Samples', name_textstyle_opts=opts.global_options.TextStyleOpts( font_size=16)), xaxis_opts=opts.AxisOpts( name=xaxis_caption, name_textstyle_opts=opts.global_options.TextStyleOpts( font_size=16))) # Data (y axis) for range_group in range_groups: # Add values on the yaxis for each file type. # If the count is 0, replace it by None to avoid overlapped numbers in the chart. chart.add_yaxis(range_group.file_type, range_group.counts, category_gap=bar_gap, stack="stack1") # Captions (x axis) chart.add_xaxis(range_groups[0].captions) chart.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) return chart
def create_likes(df): # 排序,降序 df = df.sort_values('likes', ascending=False) # 获取TOP10的数据 attr = df['name'][0:10] v1 = [float('%.1f' % (float(i) / 100000000)) for i in df['likes'][0:10]] # 初始化配置 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) # x轴数据 bar.add_xaxis(list(reversed(attr.tolist()))) # y轴数据 bar.add_yaxis("", list(reversed(v1))) # 设置全局配置项,标题、工具箱(下载图片)、y轴分割线 bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V点赞数TOP10(亿)", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) # 设置系列配置项,标签样式 bar.set_series_opts(label_opts=opts.LabelOpts( is_show=True, position="right", color="black")) bar.reversal_axis() bar.render("抖音大V点赞数TOP10(亿).html")
def create_cut_likes(df): # 将数据分段 Bins = [ 0, 1000000, 5000000, 10000000, 25000000, 50000000, 100000000, 5000000000 ] Labels = [ '0-100', '100-500', '500-1000', '1000-2500', '2500-5000', '5000-10000', '10000以上' ] len_stage = pd.cut(df['likes'], bins=Bins, labels=Labels).value_counts().sort_index() # 获取数据 attr = len_stage.index.tolist() v1 = len_stage.values.tolist() # 生成柱状图 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) bar.add_xaxis(attr) bar.add_yaxis("", v1) bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V点赞数分布情况(万)", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=True, position="top", color="black")) bar.render("抖音大V点赞数分布情况(万).html")
def create_abroad(df): # 筛选数据 df = df[(df["country"] != "中国") & (df["country"] != "") & (df["country"] != "暂不设置") & (df["country"] != "China")] df1 = df.copy() # 数据替换 df1["country"] = df1["country"].str.replace("United States", "美国").replace("大韩民国", "韩国") # 分组计数 df_num = df1.groupby("country")["country"].agg( count="count").reset_index().sort_values(by="count", ascending=False) df_country = df_num[:8]["country"].values.tolist() df_count = df_num[:8]["count"].values.tolist() # 初始化配置 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) bar.add_xaxis(df_country) bar.add_yaxis("", df_count) bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V国外分布TOP10", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=True, position="top", color="black")) bar.render("抖音大V国外分布TOP10.html")
def create_avg_likes(df): # 筛选 df = df[df['videos'] > 0] # 计算单个视频平均点赞数 df.eval('result = likes/(videos*10000)', inplace=True) df['result'] = df['result'].round(decimals=1) df = df.sort_values('result', ascending=False) # 取TOP10 attr = df['name'][0:10] v1 = ['%.1f' % (float(i)) for i in df['result'][0:10]] # 初始化配置 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) # 添加数据 bar.add_xaxis(list(reversed(attr.tolist()))) bar.add_yaxis("", list(reversed(v1))) # 设置全局配置项,标题、工具箱(下载图片)、y轴分割线 bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V平均视频点赞数TOP10(万)", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) # 设置系列配置项 bar.set_series_opts(label_opts=opts.LabelOpts( is_show=True, position="right", color="black")) # 翻转xy轴 bar.reversal_axis() bar.render("抖音大V平均视频点赞数TOP10(万).html")
def show(x: list, y: list, title: str = "键盘键入统计"): bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.WONDERLAND)) bar.add_xaxis(x) bar.add_yaxis("", y, category_gap="60%") bar.set_series_opts( itemstyle_opts={ "normal": { "color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: 'rgba(0, 244, 255, 1)' }, { offset: 1, color: 'rgba(250, 177, 160, 1)' }], false)"""), "barBorderRadius": [30, 30, 30, 30], "shadowColor": "rgb(0, 160, 221)", } }) bar.set_global_opts( title_opts=opts.TitleOpts(title=title), datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], ) bar.load_javascript() bar.render_notebook() return Markup(bar.render_embed())
def __plot_con_notebook(self, split_n)->pyecharts.charts.Bar: """ 调用echarts,连续变量 :param split_n: :return: """ data = self.data[~np.isnan(self.X)] data.sort_values('X',inplace=True) X = data['X'].values y = data['y'].values max_x = max(X) min_x = min(X) freq,edge = np.histogram(X, np.linspace(min_x, max_x, split_n+1)) freq = np.round(freq/data.shape[0] *100,2) # print(freq) # print(edge) bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK)) bar.load_javascript() bar.add_xaxis([('(' + str(int(edge[i])) + ' , ' + str(int((edge[i + 1]))) + ']') if i else ( '[' + str(int(edge[i])) + ' , ' + str(int((edge[i + 1]))) + ']') for i in range(len(edge) - 1)]) bar.add_yaxis(self.var_name, freq.tolist(), category_gap=1, ) bar.set_global_opts(title_opts=opts.TitleOpts(title=self.var_name), datazoom_opts=opts.DataZoomOpts(is_show=True), xaxis_opts=opts.AxisOpts(name_location='end', name='Groups'), yaxis_opts=opts.AxisOpts(name_location='end', name='%'), ) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True)) return bar
def generate_top_bar_html(rows, title): xx1 = [] yy1 = [] for row in rows: xx1.append(row[0].replace('转债', '')) yy1.append(row[1]) bar = Bar(init_opts=opts.InitOpts( height='700px', width='1424px', theme=ThemeType.SHINE)) # 底部x轴 bar.add_xaxis(xx1) bar.add_yaxis( '价格(元)', yy1, bar_width=25, category_gap='1%', gap='1%', label_opts=opts.LabelOpts(position="top", ), ) bar.set_series_opts(itemstyle_opts=opts.ItemStyleOpts( color=JsCode("function(x){return x.data>0?'#c23531':'#1d953f'}"))) bar.set_global_opts( title_opts=opts.TitleOpts( title="=========" + title + "=========", pos_left='center', pos_top='-1px', ), tooltip_opts=opts.TooltipOpts(is_show=False), legend_opts=opts.LegendOpts(is_show=False), xaxis_opts=opts.AxisOpts( # data=None, # type_='category', # name_gap=0, # name_rotate=90, axislabel_opts=opts.LabelOpts(rotate=-60, ), is_scale=True, name_location='middle', splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=True, # symbol=['none', 'arrow'] )), yaxis_opts=opts.AxisOpts( type_='value', name='价格(元)', # name_rotate=90, name_gap=40, name_location='middle', # min_=0, is_scale=True, # axislabel_opts=opts.LabelOpts(formatter='{value}%'), splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=False, # symbol=['none', 'arrow'] )), ) bar_html = bar.render_embed('template.html', html_utils.env) return bar_html
def drawbar(arrt, value, name): # 图表初始化配置 init_opts = opts.InitOpts(page_title=name, height="700px") bar = Bar(init_opts=init_opts) # 标题配置 title = opts.TitleOpts(title=name, pos_left='center') # 图例配置 legend_opts = opts.LegendOpts(pos_top="5%", pos_left="15%") # 工具箱配置 # feature = opts.ToolBoxFeatureOpts(save_as_image=True, restore=True, data_view=True, data_zoom=True) # 工具箱配置 toolbox_opts = opts.ToolboxOpts(pos_top="5%", pos_right="30%") bar.set_global_opts( title_opts=title, legend_opts=legend_opts, toolbox_opts=toolbox_opts, # 区域缩放配置项 datazoom_opts=opts.DataZoomOpts(), ) # add_yaxis bar.add_xaxis(arrt) # 渐变色 bar.add_yaxis( "", value, gap="0%", category_gap="30%", # 自定义颜色 itemstyle_opts=opts.ItemStyleOpts( color=JsCode("""new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: 'rgb(39, 117, 182)' }, { offset: 0.5, color: 'rgb(147, 181,207)' }, { offset: 1, color: 'rgb(35, 118, 183)' }], false)""")), ) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="min", name="最小值"), opts.MarkLineItem(type_="max", name="最大值"), opts.MarkLineItem(type_="average", name="平均值"), ]), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), opts.MarkPointItem(type_="average", name="平均值"), ]), ) bar.render('{0}.html'.format(name))
def bar(x, y, x_name, y_name): bar = Bar(init_opts=opts.InitOpts(height="600px", width="1200px")) bar.add_xaxis(xaxis_data=x) bar.add_yaxis(series_name='每年上架數量', yaxis_data=y) bar.set_global_opts(title_opts=opts.TitleOpts(title='數量'), xaxis_opts=opts.AxisOpts(name=x_name), yaxis_opts=opts.AxisOpts(name=y_name)) bar.set_series_opts(label_opts=opts.LabelOpts(position='right')) bar.reversal_axis() return bar
def render(self) -> Bar: bar = Bar() bar.add_xaxis(self.balance_axis.x_axis) bar.add_yaxis("支出", self.balance_axis.y_axis_a, category_gap="20%") bar.add_yaxis("收入", self.balance_axis.y_axis_b, category_gap="20%") bar.set_global_opts(title_opts=opts.TitleOpts(title=self.title, ), datazoom_opts=[opts.DataZoomOpts(range_start=0, range_end=100), opts.DataZoomOpts(type_="inside")], tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='shadow')) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) return bar
def bar_stack0(): obj_bar = Bar() obj_bar.add_xaxis(Faker.choose()) # stack该参数设置 obj_bar.add_yaxis("A", Faker.values(),stack="stack1") obj_bar.add_yaxis("B", Faker.values(),stack="stack1") # 设置标签不显示 obj_bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) obj_bar.set_global_opts( title_opts=opts.TitleOpts(title="Bar-堆叠数据(全部)", subtitle="副标题"),) return obj_bar
def bar_reversal_axis(): obj_bar = Bar() obj_bar.add_xaxis(Faker.choose()) obj_bar.add_yaxis("A", Faker.values()) obj_bar.add_yaxis("B", Faker.values()) # 设置翻转 XY 轴 obj_bar.reversal_axis() # 设置标签靠右显示 obj_bar.set_series_opts(label_opts=opts.LabelOpts(position="right")) obj_bar.set_global_opts( title_opts=opts.TitleOpts(title="Bar-翻转 XY 轴", subtitle="副标题"),) return obj_bar
def paintGraph(contestInfo, starttime='2017-09', endtime='2020-07'): # 先根据指定的起始日期和截止日期构造需要的数据 x, cf, ac, nc, jsk, total = [], [], [], [], [], [] for key, value in sorted(contestInfo.items()): if key >= starttime and key <= endtime: x.append(key) cf.append({'value': value.get('cf', 0)}) ac.append({'value': value.get('ac', 0)}) nc.append({'value': value.get('nc', 0)}) jsk.append({'value': value.get('jsk', 0)}) total.append(value.get('total', 0)) # print(total) # 绘制图表 bar = Bar( init_opts=opts.InitOpts(theme=ThemeType.LIGHT, page_title='各年月比赛数量统计')) bar.set_global_opts(title_opts=opts.TitleOpts(title='各年月比赛数量统计'), xaxis_opts=opts.AxisOpts(name='比赛年月'), yaxis_opts=opts.AxisOpts(name='比赛数量统计')) bar.add_xaxis(x) bar.add_yaxis("CodeForces", cf, stack="stack1", category_gap="50%") bar.add_yaxis("NowCoder", nc, stack="stack1", category_gap="50%") bar.add_yaxis("AtCoder", ac, stack="stack1", category_gap="50%") bar.add_yaxis("计蒜客", jsk, stack="stack1", category_gap="50%") bar.set_series_opts(label_opts=opts.LabelOpts( position="inside", formatter=JsCode( "function(x){return x.data.value ? Number(x.data.value) : '';}"), )) line = Line() line.set_global_opts( tooltip_opts=opts.TooltipOpts(is_show=False), xaxis_opts=opts.AxisOpts(type_="category"), yaxis_opts=opts.AxisOpts( type_="value", axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), ), ) line.add_xaxis(xaxis_data=x) line.add_yaxis( series_name="total", y_axis=total, symbol="Circle", is_symbol_show=True, label_opts=opts.LabelOpts(is_show=True), ) # 将柱状图与折线图一起输出到html文件中 bar.overlap(line).render('acmersite02.html')
def bar_markline_type(): obj_bar = Bar() obj_bar.add_xaxis(Faker.choose()) obj_bar.add_yaxis("商家A",Faker.values()) obj_bar.add_yaxis("商家B",Faker.values()) obj_bar.set_series_opts( label_opts=opts.LabelOpts(is_show = False), markline_opts=opts.MarkPointOpts( data = [opts.MarkLineItem(y=50, name="yAxis=50")] ) ) obj_bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-MarkLine(自定义)", subtitle="自定义的线")) return obj_bar
def dsp_her(): # 显示遗传力 # page = Page(layout=Page.DraggablePageLayout) import xlrd # file = "breeding.xlsx" f1 = xlrd.open_workbook(file) sheet1 = f1.sheet_by_name('Sheet1') lst = her(file) # 接收计算的遗传力 y = [] colorArr = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ] for i in range(len(lst)): color = "#" for j in range(6): color += colorArr[random.randint(0, 14)] y.append( opts.BarItem( value=lst[i], itemstyle_opts=opts.ItemStyleOpts(color=str(color)), # itemstyle_opts=opts.ItemStyleOpts(color=color[i]) )) x_ax = [] y_ax = [] start = load_profile()[0] end = load_profile()[1] for i in range(start, end + 1): x_ax.append(sheet1.cell_value(0, i)) bar = Bar(init_opts=opts.InitOpts( #bg_color='rgba(155,250,205,0.2)', width="1800px", height="800px")) bar.set_colors(["#FF6347", "black"]) # FF6347 bar.add_xaxis(x_ax) bar.add_yaxis("遗传力", y, category_gap="60%") bar.set_series_opts( label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(type_="max", name="最大值")])) # bar.add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49]) bar.set_global_opts(title_opts=opts.TitleOpts(title="显示已有数据遗传力")) for i in range(sheet1.nrows - 1): y_ax.append(i) line = Line(init_opts=opts.InitOpts(width="1800px", height="800px")) line.add_xaxis(y_ax) line.add_yaxis(series_name="", y_axis=lst, label_opts=opts.LabelOpts(is_show=True)) picture = bar.overlap(line) return render_template("display.html", picture_options=picture.dump_options())
def show_bar_figure(self, figure_name, title): bar = Bar(init_opts=opts.InitOpts(bg_color='white')) bar.add_xaxis(self.x_axis) for y_set in self.y_input_sets: self.format_yaxis(y_set) # for y_set in self.y_output_sets: # self.format_yaxis(y_set, self.top, -1, 1) for idx, y_axis in enumerate(self.y_axiss[:self.top]): bar.add_yaxis("", y_axis, gap="0", stack="stack{}".format(idx)) # for idx, y_axis in enumerate(self.y_axiss[self.top:]): # bar.add_yaxis("", y_axis, gap="0", stack="stack{}".format(idx)) bar.set_global_opts(title_opts=opts.TitleOpts(title=title, pos_left="center"), ) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False), ) bar.render(figure_name)
def bar(keywords): xaxis = [] yaxis = [] for i in keywords: xaxis.append(i[0]) yaxis.append(i[1]) bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.WALDEN)) bar.add_xaxis(xaxis[:25]) bar.add_yaxis("重要性", yaxis[:25]) bar.set_global_opts(title_opts=opts.TitleOpts(title='TF-IDF Ranking')) bar.set_global_opts(toolbox_opts=opts.ToolboxOpts(is_show=True)) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) bar.reversal_axis() return bar
def show_bar(id): fix_data() bar = Bar(init_opts=opts.InitOpts( width='1200px', height='800px', page_title='page')) bar.add_xaxis(fix_id) bar.add_yaxis('线程', fix_time, stack="stack1", color=Faker.rand_color()) bar.reversal_axis() bar.set_global_opts(title_opts=opts.TitleOpts(title="压测时间图"), datazoom_opts=opts.DataZoomOpts(orient="vertical")) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), opts.MarkPointItem(type_="average", name="平均值"), ])) bar.render('压力测试{}.html'.format(id + 1))
def bar_chart(): # 柱状图 bar = Bar() x_y_axis = get_chart_data() bar.add_xaxis(x_y_axis[0]) for j in x_y_axis[1]: for key, value in j.items(): bar.add_yaxis(key, value, label_opts=opts.LabelOpts(is_show=False)) bar.set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ]), ) bar.set_global_opts( title_opts=opts.TitleOpts( title="API耗时统计", subtitle="生产环境", pos_left="30%", title_textstyle_opts=opts.TextStyleOpts(color='red'), subtitle_textstyle_opts=opts.TextStyleOpts(color='blue')), xaxis_opts=opts.AxisOpts( name="运行时间", type_="category", boundary_gap=True, # axislabel_opts=opts.LabelOpts(rotate=15) ), yaxis_opts=opts.AxisOpts(name="实际的响应时间(单位:秒)", # min_=0, # max_=20 ), legend_opts=opts.LegendOpts(type_='scroll', selected_mode='multiple', pos_left='right', pos_top='10%', orient='vertical'), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"), toolbox_opts=opts.ToolboxOpts(is_show=True, pos_left='right'), visualmap_opts=opts.VisualMapOpts(is_show=True, type_="size", min_=0, max_=20, range_text=["最大值", "最小值"]), datazoom_opts=[opts.DataZoomOpts(range_start=50, range_end=100)], ) bar = bar.dump_options_with_quotes() return bar
def create_percent_stack_bar(title, x_list, data_list, data_unit): """ :param title: 图表名称 :param x_list: 横坐标内容为时间序列,纵坐标高度为多个(同级)指标的总和,具体各个指标的数值、比例以不同颜色标出 :param data_list: 字典{key1:value1,key2:value2...},构成柱状图的多个不同类型的bar :param data_unit: y轴的数值单位 :return: """ # 数据格式重构: count = len(x_list) # 数据期数 sumList = [] # 汇总 for i in range(count): sumList.append(0) for key in data_list.keys(): for i in range(count): if data_list[key][i] is not None: # 空数据处理 sumList[i] = sumList[i] + data_list[key][i] for key in data_list.keys(): value_list = [] for i in range(count): new_dic = {} new_dic["value"] = data_list[key][i] if data_list[key][i] is not None: # 空数据处理,sumList[i]不会为None或为0,指标选择时已经做了规避 new_dic["percent"] = data_list[key][i]/sumList[i] else: new_dic["percent"] = None value_list.append(new_dic) data_list[key] = value_list c = Bar(init_opts=opts.InitOpts(theme=THEME_TYPE)) c.add_xaxis(x_list) for key in data_list.keys(): c.add_yaxis(key, data_list[key],stack="stack1") # stack参数设置层叠样式 c.set_series_opts(label_opts=opts.LabelOpts(position="right", formatter=JsCode( "function(x){console.log(x);return Number(x.data.percent * 100).toFixed() + '%';}" ))) c.set_global_opts(title_opts=opts.TitleOpts(title=title), legend_opts=opts.LegendOpts(pos_left="right"), yaxis_opts=opts.AxisOpts(name="单位:" + data_unit)) src_path = "./指标-年度-图片生成/" html_file_name = src_path + title + ".html" img_file_name = src_path + title + ".png" make_snapshot(snapshot, c.render(html_file_name), img_file_name) print(img_file_name+":生成完毕...")
def process_statistics(): para = {'size': 80} data_source = requests.post("http://localhost:7000/es_virus_data", data=json.dumps(para)).json() # 得出地理信息/感染数量/ confirmedCount_province_list = {} suspectedCount_province_list = {} curedCount_province_list = {} deadCount_province_list = {} for source in province_souce['hits']['hits']: base = source['_source'] provinceShortName = base['provinceShortName'] confirmedCount = base['confirmedCount'] suspectedCount = base['suspectedCount'] curedCount = base['curedCount'] deadCount = base['deadCount'] # print('{}-{}-{}-{}-{}'.format(provinceShortName,confirmedCount,suspectedCount,curedCount,deadCount)) if provinceShortName not in confirmedCount_province_list.keys(): confirmedCount_province_list[provinceShortName] = int( confirmedCount) if provinceShortName not in suspectedCount_province_list.keys(): suspectedCount_province_list[provinceShortName] = int( suspectedCount) if provinceShortName not in curedCount_province_list.keys(): curedCount_province_list[provinceShortName] = int(curedCount) if provinceShortName not in deadCount_province_list.keys(): deadCount_province_list[provinceShortName] = int(deadCount) provinces = list(confirmedCount_province_list.keys()) confirm_list = list(confirmedCount_province_list.values()) suspect_list = list(suspectedCount_province_list.values()) cure_list = list(curedCount_province_list.values()) dead_list = list(deadCount_province_list.values()) # bar = Line() bar = Bar() bar.add_xaxis(provinces) bar.add_yaxis("确诊", confirm_list, stack="stack1") bar.add_yaxis("疑似", suspect_list, stack="stack1") bar.add_yaxis("治愈", cure_list, stack="stack1") bar.add_yaxis("死亡", dead_list, stack="stack1") bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True)) bar.set_global_opts(title_opts=opts.TitleOpts(title="省份疫情统计")) return bar # if __name__ == '__main__': # process_statistics()
def draw_balance_bar(xaxis, yaxis, difference=None, title="消费统计", markline=None, width=2000) -> Bar: """ x = [月_日, 月_日, 月_日, ....] y = [(title1, [num1, num2, num3, num4, ...]), (title2, [num1, num2, num3, num4, ...])] :param difference: 差值 (比如:收入100,消费80,差值就是20) : ['title', [1,2,3,4]] :param xaxis: x轴 :param yaxis: y轴 :param title: 标题 :param markline: 标记辅助线 :param width: 宽 :return: Bar """ bar = Bar() bar.add_xaxis(xaxis) for name, axis in yaxis: bar.add_yaxis(name, axis, category_gap="20%", gap="0%") bar.set_global_opts(title_opts=opts.TitleOpts(title=title, ), datazoom_opts=[ opts.DataZoomOpts(range_start=0, range_end=100), opts.DataZoomOpts(type_="inside") ], tooltip_opts=opts.TooltipOpts( trigger='axis', axis_pointer_type='shadow')) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) if difference: name, diff_yaxis = difference line = Line().add_xaxis(xaxis).add_yaxis( name, diff_yaxis, symbol_size=15, z_level=1, is_symbol_show=False, ) bar.overlap(line) if markline is not None: bar.set_series_opts(markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=markline, name='预算')])) return bar