示例#1
0
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")
示例#2
0
def bar_multiple(x: list,
                 y: list,
                 name: list,
                 title='主标题',
                 subtitle='副标题') -> Bar:
    """
	:param x:
	:param y:
	:param name:
	:param title:
	:param subtitle:
	:return:
	### doctest
	>>> x = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
	>>> y = [[5, 20, 36, 10, 75, 90],[10, 20, 30, 40, 50, 60]]
	>>> name = ['商家A', '商家B']
	>>> title='主标题'
	>>> subtitle='副标题'
	>>> test = bar_multiple(x, y, name, title, subtitle)
	>>> hasattr(test, 'render')
	True
	"""
    if len(name) != len(y):
        raise ValueError("the paramter 'name' and 'y' must be same lenth ")

    bar_ = Bar()
    bar_.add_xaxis(x)
    try:
        [bar_.add_yaxis(name[i], y[i]) for i in range(len(name))]
    except:
        raise
    bar_.set_global_opts(
        title_opts=opts.TitleOpts(title=title, subtitle=subtitle))

    return bar_
示例#3
0
 def analysis_score(self):
     evaluate = {}
     with open(self.score_file, 'r', encoding='utf-8') as f:
         for i in f.readlines():
             i = re.sub(r"[A-Za-z0-9\-\:]", "", i)
             i = i.strip()  # 去掉每行的换行符
             # 如果这个没出现过,就初始化为1
             if i not in evaluate:
                 evaluate[i] = 1
                 logger.logger.debug(evaluate)
             else:
                 # 如果已经出现过了,就在自加1
                 evaluate[i] += 1
                 logger.logger.debug(evaluate)
         logger.logger.info(evaluate)
     bar = Bar()
     eva = []
     count = []
     for k, v in evaluate.items():
         if k != '':
             eva.append(k)
             count.append(v)
     bar.add_xaxis(eva)  # 柱状图x轴
     logger.logger.info('xaxis'+str(eva))
     bar.add_yaxis("评价", count)  # 柱状图y轴
     logger.logger.info('yaxis'+str(count))
     bar.set_global_opts(title_opts=opts.TitleOpts(title="隐秘的角落 豆瓣评分"))
     # 生成可视化图表
     bar.render(self.path+"\\score.html")
示例#4
0
def do_charts():
    nvshen = pd.read_csv('nvshen.csv')
    nvshen.sort_values('weight_score', ascending=False, inplace=True)
    bar = Bar()
    count_top = nvshen['count'][0:10].values.tolist()
    count_bottom = nvshen['count'][-10:-1].values.tolist()
    count = [''.join(list(filter(str.isdigit, i))) for i in count_top] + \
            [''.join(list(filter(str.isdigit, i))) for i in count_bottom]
    name_top = nvshen['name'][0:10]
    name_bottom = nvshen['name'][-10:-1]
    name = name_top.values.tolist() + name_bottom.values.tolist()
    score_top = nvshen["weight_score"][0:10]
    score_bottom = nvshen["weight_score"][-10:-1]
    score = score_top.values.tolist() + score_bottom.values.tolist()
    bar.add_xaxis(name)
    bar.add_yaxis("女神得分/百分制", score, gap="0%")
    bar.add_yaxis("打分人数/万", count, gap="0%")
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title="女神大会", subtitle="女神大排名-top10"),
        datazoom_opts=opts.DataZoomOpts(is_show=True, orient="vertical"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-45)),
        toolbox_opts=opts.ToolboxOpts())
    bar.render('女神大排名-top10.html')

    word_name = nvshen['name'].values.tolist()
    word_value = nvshen["weight_score"].values.tolist()
    words = [i for i in zip(word_name, word_value)]
    wordcloud = WordCloud()
    wordcloud.add("", words, word_size_range=[10, 40], shape='circle')
    wordcloud.render("女神词云.html")
示例#5
0
def court_pri(keys, values1):
    dict = {}
    for result in results:
        if (result["court"] in keys) and result["court"] not in dict.keys():
            dict[result["court"]] = [result["unit_Price"]]
        elif (result["court"] in keys) and result["court"] in dict.keys():
            dict[result["court"]].append(result["unit_Price"])
    keys1 = list(dict.keys())
    values = list(dict.values())
    list1 = []
    for i in range(len(values)):
        arr_mean = np.mean(values[i])
        list1.append(int(arr_mean))
    # print(values)
    # print(keys)
    # print("长度" + str(len(keys)))
    # print(list1)
    # print("长度" + str(len(list1)))
    b = Bar(init_opts=opts.InitOpts(width="900px", height="900px"))
    b.add_xaxis(keys1)
    b.add_yaxis("小区价格", list1)
    # b.add_yaxis("小区房源",values1)
    b.set_global_opts(title_opts=opts.TitleOpts(title="新乡市",
                                                subtitle="各小区平均价格"),
                      datazoom_opts=opts.DataZoomOpts(),
                      toolbox_opts=opts.ToolboxOpts())
    return b
def weather_show(path):
    # 定义时间线标题
    title = ["最高气温", "昼夜温差", "降水量"]
    # 定义查询字段
    field = ["high_temp", "differ_temp", "precipitation"]
    # 定义标记单位
    remarks = ["温度(℃)", "温度(℃)", "降水量(mm)"]
    # 定义时间线对象
    tl = Timeline()
    for i in range(3):
        # 查询数据
        name, value = WeatherTrans().get_data(field[i], field[i])
        # 统计表标题
        bar_title = "2020年3月15日全国" + title[i] + "Top 10 城市"
        # 定义柱状图对象
        bar = Bar()
        # 添加横坐标
        bar.add_xaxis(name)
        # 添加纵坐标
        bar.add_yaxis(remarks[i],
                      value,
                      label_opts=opts.LabelOpts(position="right"))
        # 绘制横向统计图
        bar.reversal_axis()
        # 添加标题
        bar.set_global_opts(title_opts=opts.TitleOpts(bar_title))
        # 将统计图添加到时间线中
        tl.add(bar, title[i])
    # 生成html文件
    tl.render(path)
示例#7
0
def draw_bar(sum_sheet):
    prov = sum_sheet[0].col_values(0, start_rowx=1, end_rowx=31)
    line = Bar()
    x1 = []
    y1 = []
    y2 = []
    for i in range(19):
        x1.append(1997 + i)
        y1.append(sum_sheet[i].cell_value(1, 1))
        y2.append(sum_sheet[i].cell_value(9, 1))
    line.add_xaxis(x1)
    line.set_global_opts(xaxis_opts=opts.AxisOpts(
        axislabel_opts=opts.LabelOpts(font_size=10, interval=0, rotate=45)))
    line.add_yaxis("Beijing", y1)
    line.add_yaxis("Shanghai", y2)
    line.render("北京上海年CO2排放量变化图.html")

    bar = Bar()
    x2 = []
    for i in range(30):
        x2.append(prov[i])
    y3 = sum_sheet[0].col_values(1, start_rowx=1, end_rowx=31)
    y4 = sum_sheet[-1].col_values(1, start_rowx=1, end_rowx=31)
    bar.add_xaxis(x2)
    bar.set_global_opts(xaxis_opts=opts.AxisOpts(
        axislabel_opts=opts.LabelOpts(font_size=10, interval=0, rotate=45)))
    bar.add_yaxis("1997", y3)
    bar.add_yaxis("2015", y4)
    bar.render("1997与2015 各省CO2年排放量对比.html")
示例#8
0
 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')
示例#10
0
    def draw_amount_bar(self):
        """
        画出股票的成交量和
        需要传入的数据是股票的["amount"
        :return:
        """
        # SC = "000021.SZ"
        Df_s1 = Read_One_Stock(self.SC).select_col("vol", "amount")
        length = Df_s1.shape[0]
        Df_s1.sort_values("trade_date", inplace=True)
        Df_s1.index = list(range(length))
        amount = np.array(Df_s1["amount"]).tolist()
        date = np.array(Df_s1["trade_date"], dtype=np.string_).tolist()

        bar = Bar()
        bar.set_global_opts(
            xaxis_opts=opts.AxisOpts(is_scale=True),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True,
                    areastyle_opts=opts.AreaStyleOpts(opacity=1)),
            ),
            datazoom_opts=[opts.DataZoomOpts()],
            title_opts=opts.TitleOpts(title="K-Line of {}".format(self.SC)))
        bar.add_xaxis(date)
        bar.add_yaxis("Amounts",
                      amount,
                      label_opts=opts.LabelOpts(is_show=False))

        bar.render("./Plots/{} Amount Bar Plot.html".format(self.SC))
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
示例#12
0
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")
示例#13
0
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")
示例#14
0
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")
示例#15
0
def plot_echart(df, type='Bar', title=None, theme='dark'):
    '''
    数据可视化
    :param df: 数据表
    :param type: 图像类型
    :param title: 图像标题
    :return: chart
    '''
    label_x = df.columns[0]
    x = list(df[label_x])
    label_y = df.columns[-1]
    y = list(df[label_y])
    chart = Bar()

    if type == 'Bar':  # 绘制柱形图
        chart = Bar(opt.InitOpts(theme=theme))
        x = list(df[label_x])  # x轴
        y = list(df[df.columns[-1]])  # y轴
        chart.add_xaxis(x)
        chart.add_yaxis(label_y, y)

    elif type == 'Pie':  # 绘制饼图
        x = df[label_x]
        chart = (Pie().add(series_name=label_y,
                           data_pair=list(zip(list(x), y))))

    # 图像设置
    chart.set_global_opts(title_opts=opt.TitleOpts(title=title),
                          toolbox_opts=opt.ToolboxOpts(is_show=True),
                          legend_opts=opt.LegendOpts(pos_bottom=1))

    return chart
 def testBar(self):
     bar = Bar()
     bar.add_xaxis(["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"])
     bar.add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105])
     bar.add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])
     bar.set_global_opts(title_opts=opts.TitleOpts(title="某商场销售情况"))
     bar.render()
示例#17
0
def create_grid_bar_and_bar(title, x_list, data_list, data_list_2, data_unit_list):
    #   1.先生成上方的柱状图
    bar1 = Bar()
    bar1.add_xaxis(x_list)
    for key in data_list.keys():
        bar1.add_yaxis(key, data_list[key])
    bar1.set_global_opts(title_opts=opts.TitleOpts(title=title),
                        legend_opts=opts.LegendOpts(pos_left="25%", pos_top="5%"),
                        yaxis_opts=opts.AxisOpts(name="单位:" + data_unit_list[0]
                                                 , is_scale=True))

    #   2.下方柱状图
    bar2 = Bar()
    bar2.add_xaxis(x_list)
    for key in data_list_2.keys():
        bar2.add_yaxis(key, data_list_2[key])
    bar2.set_global_opts(title_opts=opts.TitleOpts(title=title),
                        legend_opts=opts.LegendOpts(pos_left="25%", pos_top="55%"),
                        yaxis_opts=opts.AxisOpts(name="单位:" + data_unit_list[1],
                                                 is_scale=True))

    # 3.生成最终的组合图
    c = (
            Grid(init_opts=opts.InitOpts(theme=THEME_TYPE,height="700px"))
                .add(bar1, grid_opts=opts.GridOpts(pos_bottom="60%"))
                .add(bar2, grid_opts=opts.GridOpts(pos_top="60%"))
        )

    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+"生成完毕...")
示例#18
0
    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
示例#19
0
def relation_count():
    """
    统计每种关系的次数
    数据来源ref:https://github.com/DesertsX/gulius-projects/blob/master/3_InteractiveGraph_HongLouMeng/InteractiveGraph_HongLouMeng.json
    :return:
    """
    with codecs.open('relative.json', 'r', encoding='utf-8') as json_str:
        json_dict = json.load(json_str)
    edges = json_dict['data']['edges']
    edges_df = pd.DataFrame(edges)
    edges_rela = edges_df.label.value_counts()
    # 所有关系
    relations = edges_df.label
    relations = relations.tolist()
    relations = list(set(relations))
    # 每种关系对应的频数
    rela_counts = []
    for each in relations:
        rela_counts.append(int(edges_rela[each]))
    # 柱状图
    bar = Bar()
    bar.add_xaxis(relations)
    bar.add_yaxis('频次', rela_counts)
    bar.set_global_opts(title_opts=opts.TitleOpts(title="红楼梦关系频次表"))
    bar.render('relation_count.html')
示例#20
0
def chart_by_one_ver(by_type, pro_id, item, title, L=None):
    """
    生成项目特定版本下的不同分类的bug分布图表
    :param by_type: 分类
    :param pro_id: 项目标识
    :param L: 资源类别名称、资源bug数量组成的列表
    :param item: 图表图示
    :param title: 图表title
    :return: html格式的图表
    """
    if L is None:
        L = []
        result = getdata.get_issue_by_one_ver(by_type, pro_id)
        for v in result:
            L.append(v)
        xaxis_data = []
        yaxis_data = []
    else:
        print('L的类型必须为None,请检查')
    if len(L) != 0:
        xaxis_data = [x[0] for x in L]
        yaxis_data = [x[1] for x in L]
        v_name = [x[2] for x in L][0]
        title = ''.join([title, v_name, '版本'])
        bar = Bar()
        bar.add_xaxis(xaxis_data)
        bar.add_yaxis(item, yaxis_data)
        bar.set_global_opts(title_opts=opts.TitleOpts(title=title))
        if os.path.exists(os.path.join(chart_path, '{}.html'.format(title))):
            os.remove(os.path.join(chart_path, '{}.html'.format(title)))
        bar.render(os.path.join(chart_path, '{}.html'.format(title)))
    else:
        print('没有数据可展示')
示例#21
0
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 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')
示例#23
0
def bar_datazoom_slider(title='Bar-DataZoom(slider-水平)',width="1200px",x_data=['前天','昨天','今天'], \
        y_data = [{'name':'商家A','values':[1,6,7]}],
        toolbox_opts=opts.ToolboxOpts(),
        datazoom_opts=[opts.DataZoomOpts()]
        ) -> Bar:
    '''
    柱状图
    y_data 几根柱子,默认1根
    y_data = [{'name':'商家A','values':[1,6,7]}]

    toolbox_opts 是否展示右上方的小工具,默认展示,不展示传 None
    datazoom_opts 是否展示图表下方可拖动的进度条,默认展示,不展示传 None
    '''
    b = Bar(init_opts=opts.InitOpts(width=width))

    if len(y_data) == 1:
        b.add_yaxis(y_data[0]['name'], y_data[0]['values'])
    if len(y_data) == 2:
        b.add_yaxis(y_data[0]['name'], y_data[0]['values'])
        b.add_yaxis(y_data[1]['name'], y_data[1]['values'])

    b.add_xaxis(x_data)
    b.set_global_opts(
        title_opts=opts.TitleOpts(title=title),
        datazoom_opts=datazoom_opts,
        toolbox_opts=toolbox_opts,
    )
    return b
示例#24
0
def timeline_bar() -> Timeline:
    allBars = []
    # 共有 12 个Bar
    for (months, index) in zip(yearMonth, range(0, 11)):

        bar = Bar()
        bar.set_global_opts(title_opts=opts.TitleOpts("实验二-每月的购买力活跃程度"))
        bar.add_xaxis(['municipal'])
        for z in zip(list(np.array(rowData)[:, 0]),
                     list(np.array(rowData)[:, index + 1]),
                     list(np.array(rowBrand)[:, index + 1])):
            bar.add_yaxis(
                series_name=z[0] + z[2], yaxis_data=[z[1]]).set_global_opts(
                    title_opts=opts.TitleOpts("实验四-每月的销售最高Brand-city"),
                    legend_opts=opts.LegendOpts(
                        type_='scroll',
                        pos_left='50%',
                    ))
        allBars.append(bar)

    # 将allBars 与时间轴绑定
    tl = (Timeline().add_schema(play_interval=2000, is_auto_play=True))
    # bug:为什么后面的 bar 的x轴坐标会覆盖掉前面的bar呢
    for (itemTime, itemBar) in zip(yearMonth, allBars):
        tl.add(itemBar, itemTime)
    return tl
示例#25
0
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
示例#26
0
def create_result_chart(data):

    instrulist = list(set(d.instrument for d in data))
    # x = ["{} P{}".format(localtime(d.upload_time).strftime("%Y-%m-%d %X"), d.platenum) for d in data]
    x = ["{} P{}".format(d.upload_time.strftime("%Y-%m-%d %X"), d.platenum) for d in data]

    # 均值直方图
    b = Bar(init_opts=opts.InitOpts(width='1900px'))
    b.add_xaxis(x)
    for instru in instrulist:
        mean = get_mean(data, instru)
        b.add_yaxis(instru, mean)
    b.set_global_opts(title_opts=opts.TitleOpts(title="结果mean图"))

    # sd折线图
    l = Line(init_opts=opts.InitOpts(width='1900px'))
    l.add_xaxis(x)
    for instru in instrulist:
        sd = get_sd(data, instru)
        l.add_yaxis(instru, sd, is_connect_nones=True)
    l.set_global_opts(title_opts=opts.TitleOpts(title="结果sd图", pos_top='48%'))

    grid = Grid(init_opts=opts.InitOpts(width='1900px'))
    grid.add(b, grid_opts=opts.GridOpts(pos_bottom='60%'))
    grid.add(l, grid_opts=opts.GridOpts(pos_top='60%'))
    
    return grid
示例#27
0
文件: epidemic_bar.py 项目: noob108/-
 def print_bar(self):
     bar = Bar(init_opts=opts.InitOpts(width='1080px', height='480px'))
     bar.add_xaxis(self.timedata)
     # category 是同系列直接的距离,gap是不同系列之间的距离
     bar.add_yaxis('治愈人数',
                   self.heal,
                   gap='100%',
                   label_opts=opts.LabelOpts(is_show=False),
                   itemstyle_opts=opts.ItemStyleOpts(color='#90EE90'))
     if self.name == '湖北':
         bar.add_yaxis('死亡人数',
                       self.dead,
                       gap='100%',
                       label_opts=opts.LabelOpts(is_show=False),
                       itemstyle_opts=opts.ItemStyleOpts(color='#696969'))
     # 设置全局变量:x轴标签倾斜度,html主标题
     bar.set_global_opts(datazoom_opts=[
         opts.DataZoomOpts(),
         opts.DataZoomOpts(type_='inside')
     ],
                         toolbox_opts=opts.ToolboxOpts(),
                         xaxis_opts=opts.AxisOpts(name_rotate=-15),
                         title_opts=opts.TitleOpts(self.name,
                                                   subtitle='数据来自inews'))
     line = Line()
     line.add_xaxis(self.timedata)
     line.add_yaxis('确诊人数',
                    self.confirm,
                    label_opts=opts.LabelOpts(is_show=False),
                    itemstyle_opts=opts.ItemStyleOpts(color='#F08080'))
     print(self.name + '.html', '已成功生成到', os.getcwd())
     # 在bar的基础上画line
     bar.overlap(line).render(self.name + '.html')
示例#28
0
def theme_macarons(make_new, tag):
    tl = Timeline(init_opts=opts.InitOpts(
        theme=ThemeType.MACARONS))  # theme=ThemeType.PURPLE_PASSION
    tl.add_schema(
        pos_bottom='-7px',
        is_auto_play=True,
        symbol_size=[20, 20],
        play_interval=2000,
    )
    for i in range(2015, 2020):
        bar = Bar()
        bar.add_xaxis(list(make_new.columns))
        bar.add_yaxis("",
                      list(make_new.loc[i, :].values),
                      label_opts=opts.LabelOpts(is_show=False))
        bar.set_colors([
            random.choice([
                'blue', 'rgba(100,255,0,0.8)', '#5793f3', '#007A99', 'yellow'
            ])
        ])
        bar.set_global_opts(
            xaxis_opts=opts.AxisOpts(name="", axislabel_opts={"rotate": 40}),
            title_opts=opts.TitleOpts("{}-{}指数".format(i, tag)))

        tl.add(bar, "{}年".format(str(i)))
    return tl
示例#29
0
文件: jhplt.py 项目: D10Andy/NoteBook
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
示例#30
0
 def city_company_scale_chart(self):
     """前10城市的企业阶段"""
     city_company_scale = pd.crosstab(self.frame.city,
                                      self.frame.company_scale,
                                      margins=True).sort_values(
                                          by='All', ascending=False)[:10]
     city_company_scale = city_company_scale.drop('All',
                                                  axis=0).drop('All',
                                                               axis=1)
     html_path = os.path.join(
         create_or_get_directory(os.path.join('report', 'single')),
         'city_company_scale_chart.html')
     bar = Bar(init_opts=opts.InitOpts(width="60%"))
     bar.add_xaxis(list(city_company_scale.index))
     for i in range(len(list(city_company_scale.T.index))):
         bar.add_yaxis(city_company_scale.T.index[i],
                       [str(v) for v in city_company_scale.T.values[i]])
     bar.set_global_opts(
         legend_opts=opts.LegendOpts(is_show=False),
         xaxis_opts=opts.AxisOpts(
             axislabel_opts=opts.LabelOpts(rotate=-20, color='red')),
         yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
             color='red')),
     )
     bar.render(html_path)
     script_string = self.get_javascript_string(html_path)
     self.set_report_javascript(script_string, 'city_company_scale_chart')
     self.right_charts.append({
         'title': '前10城市的企业阶段',
         'name': 'city_company_scale_chart'
     })