예제 #1
0
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)
예제 #2
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")
예제 #3
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
예제 #4
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")
예제 #5
0
def show_score_top():
    # 查找上映年份集合
    showtime = select_showtime()
    # 生成时间轴的图
    timeline = Timeline(
        init_opts=opts.InitOpts(page_title="豆瓣电影TOP250-评分TOP10的电影", ))
    for year in showtime:
        film_tuple = select_film(year)
        date_list = select_data(year)
        timeline.add_schema(is_auto_play=True, play_interval=1000)
        # 柱状图初始化
        bar = Bar()
        # 横坐标
        bar.add_xaxis(film_tuple[0])
        # 纵坐标
        bar.add_yaxis(
            "",
            date_list,
            # 数据靠右显示
            label_opts=opts.LabelOpts(is_show=True, position='right'))
        # 横纵坐标翻转
        bar.reversal_axis()
        # 全局配置
        bar.set_global_opts(
            # 标题
            title_opts=opts.TitleOpts(
                title="豆瓣电影TOP250-第{}年评分TOP10的电影".format(year),
                pos_left='center'),
            # 横坐标隐藏
            xaxis_opts=opts.AxisOpts(is_show=False,
                                     max_=select_film(year)[2],
                                     min_=(float(select_film(year)[3]) - 0.1),
                                     split_number=10),
            # 纵坐标
            yaxis_opts=opts.AxisOpts(
                max_=9,
                # 字体大小
                axislabel_opts=opts.LabelOpts(font_size=10),
                # 隐藏坐标轴
                axisline_opts=opts.AxisLineOpts(is_show=False),
                # 隐藏刻度
                axistick_opts=opts.AxisTickOpts(is_show=False)))
        # 组合组件
        grid = (Grid().add(bar,
                           grid_opts=opts.GridOpts(pos_top='8%',
                                                   pos_bottom='12%',
                                                   pos_left='25%')))
        timeline.add(grid, "{}年".format(year))
        timeline.add_schema(is_auto_play=True,
                            play_interval=1000,
                            is_loop_play=False,
                            width='820px',
                            pos_left='60px')
    # 生成HTML
    html = "pages/iframes/score_top.html"
    timeline.render("./templates/" + html)
    return html
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
예제 #7
0
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
예제 #8
0
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))
예제 #9
0
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
예제 #10
0
파일: test.py 프로젝트: QMXDD/Crawler
    def table(self):
        file = open(self.name + "_title.txt", "r", encoding="utf-8")
        title = []
        read = []
        list = file.readlines()
        for i in list:

            pos = None
            end = i.__len__() - 1
            while end >= 0:
                if (i[end] == " "):
                    pos = end
                    break
                end -= 1
            pos2 = None
            while end >= 0:
                if (i[end] != " "):
                    pos2 = end + 1
                    break
                end -= 1

            title_str = i[:pos2]
            j = title_str.__len__()
            j = int(j / 2)
            title_str = title_str[:j] + "\n" + title_str[j:]
            title.append(title_str)

            read_str = i[pos:]
            read_str = read_str.strip()
            read.append(int(read_str))

        read_data = []
        title_data = []
        j = 0
        for i in read:
            if i > self.num:
                read_data.append(i)
                title_data.append(title[j])
            j += 1

        bar = Bar()
        bar.add_xaxis(title_data)
        bar.add_yaxis("访问量大于" + str(self.num) + "的博客", read_data)
        bar.reversal_axis()
        bar.render(self.name + ".html")
예제 #11
0
파일: epidemic_bar.py 프로젝트: noob108/-
def print_bar(confirm_frame, timelist, all_province_name):
    tl = Timeline(init_opts=opts.InitOpts(
        page_title='疫情可视化', width='1080px', height='480px'))
    # 调节播放速率 ,是否自动播放,是否循环播放,是否显示时间轴
    tl.add_schema(play_interval=300,
                  is_auto_play=True,
                  is_loop_play=False,
                  is_timeline_show=True)
    l = len(timelist)
    for i in range(0, l):
        # 将每天的数据单独拿出来进行排序
        s = {'province': all_province_name, 'confirm': confirm_frame.loc[:][i]}
        s = pd.DataFrame(s)
        # 翻转是镜像翻转所以 这里要从大到小排序
        s = s.sort_values(by='confirm', ascending=1)
        province_name = s[-10:]['province']
        confirm = s[-10:]['confirm']
        heal_list, dead_list = get_Top10info(province_name, l - i)
        bar = Bar()
        bar.add_xaxis(province_name.to_list())
        # 名字,数据,柱状图间距, label标签显示在右侧|这样翻转的时候就在右侧
        # gap 神奇的参数因为每个柱状图有固定位置|宽度l, 正代表向正向移动百分比l,负代表向负向移动百分比l
        bar.add_yaxis('确诊人数',
                      confirm.to_list(),
                      label_opts=opts.LabelOpts(position='right'),
                      color='#696969')
        bar.add_yaxis('治愈人数',
                      heal_list,
                      label_opts=opts.LabelOpts(position='right'),
                      color='#90EE90')
        bar.add_yaxis('死亡人数',
                      dead_list,
                      label_opts=opts.LabelOpts(position='right'),
                      color='#F08080')
        # 设置全局变量:x轴标签倾斜度,html主标题
        bar.set_global_opts(legend_opts=opts.LegendOpts(is_show=True),
                            xaxis_opts=opts.AxisOpts(name_rotate=-15),
                            title_opts=opts.TitleOpts('当前日期:%s' % timelist[i],
                                                      subtitle='数据来自inews'))
        bar.reversal_axis()
        tl.add(bar, timelist[i])
    name = '疫情柱状图.html'
    print(name, '已成功生成到', os.getcwd())
    tl.render(name)
예제 #12
0
    def __plot_cat_notebook(self):
        data = pd.value_counts(self.X)
        x = list(data.index.values)
        values = list(data.values / np.sum(data.values) * 100)

        bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        bar.load_javascript()

        bar.add_xaxis([i for i in x])

        bar.add_yaxis("1", [round(i, 2) for i in values])

        bar.set_global_opts(title_opts=opts.TitleOpts(title=self.var_name),
                            xaxis_opts=opts.AxisOpts(name_location='end', name='%'),
                            yaxis_opts=opts.AxisOpts(name_location='end', name='Groups'),
                            )
        bar.reversal_axis()
        bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position="right"))

        return bar
예제 #13
0
def create_comments(df):
    df = df.sort_values('comments', ascending=False)
    attr = df['name'][0:10]
    v1 = ['%.1f' % (float(i) / 100000000) for i in df['comments'][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)))
    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 draw_chart(x_data, y_data, title, page_title, series_name, floder_name,
               res):

    bar = Bar(
        InitOpts(width="1500px",
                 height="4600px",
                 page_title=page_title,
                 animation_opts=opts.AnimationOpts(
                     animation_easing='exponentialInOut')))
    bar.add_xaxis(xaxis_data=x_data)
    bar.add_yaxis(yaxis_data=y_data,
                  series_name=series_name,
                  category_gap="30%")
    bar.set_global_opts(title_opts=opts.TitleOpts(title=title + '粉丝数变化',
                                                  subtitle=res[0] + '到' +
                                                  res[1]),
                        xaxis_opts=AxisOpts(boundary_gap=['5%', '10%']),
                        toolbox_opts=opts.ToolboxOpts())
    # bar.set_global_opts(xaxis_opts=AxisOpts(boundary_gap=['5%', '10%']), toolbox_opts=opts.ToolboxOpts())
    bar.reversal_axis()
    bar.set_series_opts(label_opts=opts.LabelOpts(position="right"))
    bar.render("serve/chart/{0}/{1}.html".format(floder_name, title))
예제 #15
0
def hot_city_bar(df_data):
    """绘制热门行业Top10"""
    x = df_data[0]
    y = df_data[1]

    bar = Bar(init_opts=opts.InitOpts(
        width='720px', height='320px', theme=ThemeType.LIGHT))

    bar.add_xaxis(xaxis_data=x[::-1])
    bar.add_yaxis(series_name='热门行业的用人需求Top10', yaxis_data=y[::-1])
    bar.set_global_opts(
        # reversal_axis : 是否反向坐标轴
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(), ),
        # range_start : 开始值  百分之零到百分百
        # range_end : 结束值
        datazoom_opts=opts.DataZoomOpts(is_show=True,
                                        range_start=0,
                                        range_end=100),
        # tooltip_opts=opts.ToolBoxFeatureOpts()
        toolbox_opts=opts.ToolboxOpts(is_show=True))
    bar.reversal_axis()
    return bar
예제 #16
0
def create_reversal_bar(title, x_list, data_list, data_unit):
    """
    :param title: 图表名称
    :param x_list: 横坐标内容,具有多种情况:1.时间序列   2.指标序列
    :param data_list: 字典{key1:value1,key2:value2...},构成柱状图的多个不同类型的bar
    :param data_unit: 数值的单位
    :return:
    """
    unit = "单位:" + data_unit
    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])
    c.reversal_axis()
    c.set_series_opts(label_opts=opts.LabelOpts(position="right"))
    c.set_global_opts(title_opts=opts.TitleOpts(title=title),
                      legend_opts=opts.LegendOpts(pos_left="right"),
                      xaxis_opts=opts.AxisOpts(name=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+":生成完毕...")
예제 #17
0
 def bar_render_general(self):
     c = Bar()
     c.add_xaxis(self.x_value)
     c.add_yaxis(self.y_name,
                 self.y_value,
                 label_opts=opts.LabelOpts(is_show=self.is_show))
     if self.reversal_axis == True:
         c.reversal_axis()
     c.set_series_opts(label_opts=opts.LabelOpts(position="right"))
     c.set_global_opts(
         title_opts=opts.TitleOpts(title=self.title,
                                   subtitle=self.subtitle),
         tooltip_opts=opts.TooltipOpts(trigger="axis"),
         legend_opts=opts.LegendOpts(pos_left="center",
                                     pos_top=self.pos_top,
                                     legend_icon=self.legend_icon),
     )
     if len(self.args) > 0:
         for num in range(len(self.args[0])):
             c.add_yaxis(series_name=self.args[0][num],
                         y_axis=self.args[1][num],
                         label_opts=opts.LabelOpts(is_show=self.is_show))
     return c
예제 #18
0
def make_bar_voter_star(filename):
    """
    生成水平直方图,根据影评有用数
    :param filename:
    :return:
    """
    # 定义各个文件名
    # title = filename.split('/')[-1].split('.')[0]
    title = os.path.basename(filename).split('.')[0]
    target_dir = os.path.join(
        os.path.abspath(os.path.dirname(os.path.dirname(__file__))),
        "analyse_data", "bar_voter_star_pic")
    if not os.path.exists(target_dir):
        os.mkdir(target_dir)
    print("分析结果保存在 ", target_dir, " 文件夹下...")
    htmlName = title + '.html'
    pngName = title + '.png'
    htmlPath = os.path.join(target_dir, htmlName)
    pngPath = os.path.join(target_dir, pngName)
    # 导入数据,并删除无关列
    rows = pd.read_csv(filename, encoding='utf-8', dtype=str)
    to_drop = ['是否看过', '评论时间', '评分', '评论']
    rows.drop(to_drop, axis=1, inplace=True)
    # 数据清洗
    rows['有用数'] = rows['有用数'].astype('int')
    # 数据统计
    result_voter_star = rows.sort_values(by='有用数', ascending=True).tail(15)
    # 转换类型 pd.Series -> py.list
    values = [(i[1], i[2]) for i in result_voter_star.itertuples()]
    # pyecharts 生成水平柱状图
    bar = Bar()
    bar.add_xaxis([i[0] for i in values])
    bar.add_yaxis('影评者获认同数', [i[1] for i in values])
    bar.reversal_axis()
    bar.set_global_opts(title_opts=opts.TitleOpts(title="电影<" + title +
                                                  ">影评者影响力排行"))
    bar.render(htmlPath)
예제 #19
0
def timeline_bar_reversal(title="Timeline-Bar-Reversal", is_auto_play=True):
    '''
    动效数据增长图
    '''
    data = getExcelToData1()

    tl = Timeline()
    tl.add_schema(
        is_auto_play=is_auto_play,
        play_interval=100,
        is_loop_play=True,
        is_inverse=False,
        # axis_type='time',
        is_timeline_show=True,  # 是否展示播放按钮
    )

    # for i in range(1950, 2020):
    #     bar = Bar()
    #     bar.add_xaxis(Faker.choose())
    #     bar.add_yaxis("商家A", Faker.values(), label_opts=opts.LabelOpts(position="right"))
    #     bar.add_yaxis("商家B", Faker.values(), label_opts=opts.LabelOpts(position="right"))
    #     bar.reversal_axis()
    #     bar.set_global_opts(title_opts=opts.TitleOpts("{}: {} ".format(title,i)))
    #     tl.add(bar, "{}年".format(i))
    for i in range(1, len(data['date'])):
        bar = Bar()
        bar.add_xaxis(data['kanaal'])
        bar.add_yaxis('新增',
                      data['values'][i - 1],
                      label_opts=opts.LabelOpts(position="right"))
        bar.reversal_axis()
        bar.set_global_opts(
            title_opts=opts.TitleOpts("{}: {} ".format(title, i)))
        tl.add(bar, "{}".format(i))

    return tl
예제 #20
0
from pyecharts.charts import Bar


# In[47]:


# 条形图
bar1 = Bar(init_opts=opts.InitOpts(width='1280px', height='1000px')) 
bar1.add_xaxis(province_num.index.tolist())
bar1.add_yaxis("省份", province_num.values.tolist()) 
bar1.set_global_opts(title_opts=opts.TitleOpts(title="调剂信息发布数省份分布"), 
                     toolbox_opts=opts.ToolboxOpts(),
                     visualmap_opts=opts.VisualMapOpts(max_=110)) 
bar1.set_series_opts(label_opts=opts.LabelOpts(position='right'))  # 标签
bar1.reversal_axis() 
bar1.render_notebook()


# In[48]:


from pyecharts.charts import Map


# In[49]:


c = Map(init_opts=opts.InitOpts(width='800px', height='750px'))
c.add('',[list(z) for z in zip(province_num.index.tolist(), province_num.values.tolist())], 'china')
c.set_global_opts(title_opts=opts.TitleOpts('调剂信息省份分布地图'), 
tiji_top10 = tiji_top10.sort_values('tiji_num')
tiji_top10
# 产生数据
x_data = tiji_top10['actor_name'].values.tolist()
y_data = tiji_top10['tiji_num'].values.tolist()

# 条形图
bar3 = Bar(init_opts=opts.InitOpts(width='1350px', height='750px'))
bar3.add_xaxis(x_data)
bar3.add_yaxis('', y_data)
bar3.set_global_opts(title_opts=opts.TitleOpts(title='弹幕中演员提及次数排行Top10'),
                     visualmap_opts=opts.VisualMapOpts(max_=int(
                         max(tiji_top10['tiji_num'])),
                                                       is_show=False))
bar3.set_series_opts(label_opts=opts.LabelOpts(position='right'))
bar3.reversal_axis()
bar3.render()

page = Page()
page.add(bar1, bar2, bar3)
page.render('../image/演员请就位2弹幕分析.html')


def get_cut_words(x_series):
    # 读入停用词表
    stop_words = []

    with open(
            r"C:\Users\wzd\Desktop\CDA\CDA_Python\Python文本分析\10.文本摘要\stop_words.txt",
            'r',
            encoding='utf-8') as f:
예제 #22
0
    def pyechart_Bar_plot(self, filedata, para):
        from pyecharts.charts import Bar, Timeline
        file_name = '条形图.html'
        path_plotly = self.path_dir_plotly_html + os.sep + file_name  # 文件路径,前面是文件夹后面是文件名
        costumeTheme = self.themedict[para['theme']]
        df = pd.read_excel(filedata, sheet_name='Sheet1')
        # -----------------------------------------------------------------------
        if not para['TimeLineOn']:
            bar = (
                Bar(init_opts=opts.InitOpts(theme=costumeTheme,
                                            width=para['width'],
                                            height=para['height']))
                # ThemeType.LIGHT para['theme']
            )
            chart = bar
            columns = df.columns.values.tolist()
            xlabel = columns[0]
            xdata = df[xlabel].values.tolist()

            chart.add_xaxis(xaxis_data=xdata)
            for i in range(1, len(columns)):
                ylabel = columns[i]
                ydata = df[ylabel].values.tolist()
                chart.add_yaxis(series_name=ylabel, y_axis=ydata)
            if para['x2y']:
                chart.reversal_axis()
            self.Common_code(chart, path_plotly, para)
        else:
            Timewhole = df['时间'].values.tolist()
            Timevalid = df['时间'].dropna().tolist()

            index = []
            for i in Timevalid:
                index.append(Timewhole.index(i))
            index.append(len(df))
            print(index)

            columns = df.columns.values.tolist()

            Timel = Timeline().add_schema(
                symbol='arrow',
                play_interval=1000  # 单位为毫秒
            )

            for j in range(len(index) - 1):

                chart = Bar()

                # 数据切片
                m = index[j]
                n = index[j + 1]
                xlabel = columns[1]
                xdata = df[xlabel].values.tolist()[m:n]

                chart.add_xaxis(xaxis_data=xdata)

                for i in range(2, len(columns)):
                    ylabel = columns[i]
                    ydata = df[ylabel].values.tolist()[m:n]
                    chart.add_yaxis(series_name=ylabel, y_axis=ydata)
                if para['x2y']:
                    chart.reversal_axis()

                Timel.add(chart, "{}".format(Timevalid[j]))
                self.Common_code(chart, path_plotly, para)
                Timel.render(path_plotly)

        print('成功绘制条形图')
        return path_plotly  # 返回该HTML文件路径
예제 #23
0
x_vals2 = ['POLO', '篮球鞋', '羽绒服', '皮鞋', '领带', '睡衣']
x_vals3 = ['羽毛球服', '羽毛球鞋', '护腕', '护膝', '护踝', '毛巾']
y_vals = [random.randint(10, 100) for _ in range(18)]
bar = Bar().add_xaxis(x_vals1 + x_vals2 + x_vals3)
bar.add_yaxis('商家A',
              y_vals,
              markpoint_opts=opts.MarkPointOpts(data=[
                  opts.MarkPointItem(type_='average'),
                  opts.MarkPointItem(type_='max'),
                  opts.MarkPointItem(type_='min')
              ],
                                                symbol_size=80))
bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='right'))
bar.set_global_opts(
    title_opts=opts.TitleOpts(title='条形图示例-商品销量', subtitle='条目较多条形图比较好看点'))
bar.reversal_axis()  #翻转XY轴,将柱状图转换为条形图
bar.render('条形图.html')

# 直方图
import random
import pyecharts.options as opts
from pyecharts.charts import Bar
x_vals = ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
xlen = len(x_vals)

# 设置成两种颜色
y_vals = []
for idx, item in enumerate(x_vals):
    if idx % 2 == 0:
        y_vals.append(
            opts.BarItem(
예제 #24
0
    def plot_ground_truth_analysis(
        all_score_columns: typing.List[str],
        title: str,
        output_path: str,
        df: pd.DataFrame,
        add_wrong_candidates: bool = False,
        wrong_candidates_score_column: str = None,
    ) -> None:
        """
        use pyechart to plot html interactive figure
        """
        df_processed = copy.deepcopy(df)
        for each_col in df_processed.columns:
            df_processed[each_col] = pd.to_numeric(df_processed[each_col],
                                                   errors='ignore')

        xaxis_labels = []
        memo = defaultdict(list)

        groupby_res = df_processed[df_processed["evaluation_label"] ==
                                   1].groupby(["column", "row"])
        for key, each_group in reversed(tuple(groupby_res)):
            if add_wrong_candidates:
                df_wrong_examples = df_processed[(df_processed["column"] == key[0]) &
                                                 (df_processed["row"] == key[1]) &
                                                 (df_processed["evaluation_label"] == -1)] \
                                        .sort_values(by=[wrong_candidates_score_column], ascending=False).iloc[:3, :]
                # add wrong candidate information
                for _, each_row in df_wrong_examples.iterrows():
                    longest_string = max(each_row["kg_labels"].split("|"),
                                         key=len)
                    xaxis_labels.append(each_row["label_clean"] +
                                        " \n({})".format(longest_string))
                    for each_score_column in all_score_columns:
                        memo[each_score_column].append("{:.2f}".format(
                            each_row[each_score_column]))

            # add ground truth information
            xaxis_labels.append(each_group["label_clean"].iloc[0])
            for each_score_column in all_score_columns:
                memo[each_score_column].append("{:.2f}".format(
                    each_group[each_score_column].iloc[0]))
        # build figure
        bar = Bar()
        bar.add_xaxis(xaxis_labels)
        for k, v in memo.items():
            bar.add_yaxis(k, v)

        # set the global options
        bar.set_global_opts(
            title_opts=opts.TitleOpts(title=title, pos_left='40%'),
            legend_opts=opts.LegendOpts(pos_left="center",
                                        pos_top="bottom",
                                        orient='horizontal'),
            brush_opts=opts.BrushOpts(),
            toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts(
                save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(
                    title="save as image"),
                magic_type=opts.ToolBoxFeatureMagicTypeOpts(
                    line_title="switch to line chart",
                    bar_title="switch to bar chart",
                    stack_title="switch to stacked values",
                    tiled_title="switch to tiled values"),
                data_zoom=opts.ToolBoxFeatureDataZoomOpts(
                    zoom_title="zoom in", back_title="zoom reset"),
                restore=opts.ToolBoxFeatureRestoreOpts(title="reset"),
                data_view=opts.ToolBoxFeatureDataViewOpts(
                    title="Data table view",
                    lang=["Table view", "Close", "Refresh"],
                ),
                brush=opts.ToolBoxFeatureBrushOpts(
                    rect_title="rectangle choice",
                    polygon_title="polygon choice",
                    clear_title="clear choices",
                    keep_title="keep choices"))),
            datazoom_opts=opts.DataZoomOpts(orient="vertical"),
            # yaxis_opts=opts.AxisOpts(name='labels', name_gap=5000, name_rotate=15),
            tooltip_opts=opts.TooltipOpts(is_show=True,
                                          trigger="axis",
                                          axis_pointer_type="shadow"),
            xaxis_opts=opts.AxisOpts(axistick_opts=opts.AxisTickOpts(
                is_inside=True,
                length=850,
                linestyle_opts=opts.LineStyleOpts(type_="dotted",
                                                  opacity=0.5))))

        # do not shown bar label values
        bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

        bar.reversal_axis()

        grid = (Grid(init_opts=opts.InitOpts(
            width="1500px",
            height="1000px",
            page_title="Table Linker visualization page")).add(
                bar,
                grid_opts=opts.GridOpts(pos_top='5%',
                                        pos_bottom="10%",
                                        pos_right='5%',
                                        pos_left="20%")))
        grid.render(output_path + ".html")
def draw_bar_reverse_picture(xaxis_data,
                             data,
                             to_file,
                             unit,
                             svg_name,
                             stack,
                             y_name,
                             pos_left='25%'):
    """
    多个y列,是否堆叠要确认下
    :param pos_left: "25%"
    :param is_reverse: xy轴是否反转
    :param y_name: y轴名称
    :param stack: boolean, 是否要堆叠
    :param xaxis_data: x轴
    :param data: {series_name, data}
    :param svg_name: svg文件
    :param to_file: 结果文件
    :param unit: 横轴的数值的单位(加在每个横轴值后面,比如 月)
    :return:
    """
    xaxis_data = [str(i) + unit for i in xaxis_data]
    bar = Bar(init_opts=opts.InitOpts(
        width="800px", height="600px", bg_color='white')).add_xaxis(  # 1250px
            xaxis_data=xaxis_data,
            # add_xaxis=opts.LabelOpts(formatter="{value}" + unit),
        )
    for series_name, y_axis in data.items():
        if stack:
            bar = bar.add_yaxis(
                series_name=series_name,
                stack='1',
                # color="#d14a61",
                y_axis=y_axis,
                yaxis_index=0,
                label_opts=opts.LabelOpts(is_show=False),
            )
        else:
            bar = bar.add_yaxis(
                series_name=series_name,
                color="#61a0a8",
                category_gap='50%',
                y_axis=y_axis,
                yaxis_index=0,
                label_opts=opts.LabelOpts(is_show=True, position='right'),
            )
    bar = bar.set_global_opts(
        yaxis_opts=opts.AxisOpts(
            type_="category",
            # min_=0,
            # max_=250,
            position="left",
            offset=0,
            axisline_opts=opts.AxisLineOpts(
                linestyle_opts=opts.LineStyleOpts()),
            axislabel_opts=opts.LabelOpts(formatter="{value}", font_size=20),
        ),
        xaxis_opts=opts.AxisOpts(
            name=y_name,
            name_textstyle_opts=opts.TextStyleOpts(font_size=20),
            axislabel_opts=opts.LabelOpts(formatter="{value}", font_size=20),
        ),
        tooltip_opts=opts.TooltipOpts(trigger="axis",
                                      axis_pointer_type="cross"),
        toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts(
            data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False),
            # brush=opts.ToolBoxFeatureBrushOpts(is_show=False),
        )),
        legend_opts=opts.LegendOpts(is_show=False),
    )
    bar = bar.reversal_axis()
    grid = (
        Grid(init_opts=opts.InitOpts(width="800px",
                                     height="600px",
                                     bg_color='rgb(255, 255, 255)'))  # 800px
        .add(bar,
             grid_opts=opts.GridOpts(pos_left=pos_left),
             is_control_axis_index=True))
    make_snapshot(snapshot, grid.render(to_file), svg_name)  # 生成svg图片
예제 #26
0
파일: demo.py 프로젝트: William-2000/bili
def bilibiliData_demo():
    # 获取B站排行榜数据
    bilibilidata.getRank()
    os.chdir(r'C:\Users\William\Desktop\bili\bilibili_data')
    rank_data = pd.read_csv('all.csv')
    print('成功获取排行榜数据')
    rank_url = rank_data.url
    rank_title = rank_data.title

    url_head = r'https:'
    for i in range(len(rank_url)):
        rank_url[i] = url_head + rank_url[i]

    # 爬取排行榜每一个视频的基本信息
    # print('正在爬取排行榜每一个视频的基本信息')
    # process_num = 1
    # for each in rank_url:
    #     try:
    #         os.chdir(r'C:\Users\William\Desktop\bili')
    #         video = VideoData(each)
    #         print(i)
    #         i += 1
    #     except:
    #         i+=1

    danmaku_list = list()
    replies_list = list()
    favorite_list = list()
    coin_list = list()
    like_list = list()

    for each in rank_title:
        each_video_info = list()
        try:
            os.chdir(
                r'C:\Users\William\Desktop\bili\videos_data\{}'.format(each))
            info = pd.read_csv('video_info.csv')
        except Exception as exc:
            print('无法打开文件')
            continue
        print('成功获取文件')

        info = pd.DataFrame(info.values.T)
        danmaku_list.append(int(info[5][1]))  # 弹幕
        replies_list.append(int(info[6][1]))  # 评论
        favorite_list.append(int(info[7][1]))  # 收藏
        coin_list.append(int(info[8][1]))  # 投币
        like_list.append(int(info[9][1]))  # 喜爱

    x_axis = list(range(100, 0, -1))
    bar = Bar(init_opts=opts.InitOpts(
        width='1600px', height='900px', theme=ThemeType.WALDEN))

    bar.add_xaxis(x_axis)
    bar.add_yaxis('弹幕', danmaku_list)
    bar.add_yaxis('评论', replies_list, is_selected=False)
    bar.add_yaxis('收藏', favorite_list, is_selected=False)
    bar.add_yaxis('投币', coin_list, is_selected=False)
    bar.add_yaxis('喜爱', like_list, is_selected=False)
    bar.reversal_axis()

    bar.set_global_opts(datazoom_opts=opts.DataZoomOpts(orient='vertical'))

    os.chdir(r'C:\Users\William\Desktop\bili')
    bar.render('排行榜数量分布图.html')
    make_snapshot(snapshot, bar.render(), '排行榜数量分布图.png')
def barChart(df):
    type_of_plot = st.selectbox("Select Type of Plot",["BAR1","BAR2","BAR3","BAR4","BAR5"])
    all_columns = df.columns
    
        
        #st.success("Generating Customizable Plot of {} for {}".format(type_of_plot))
        
    if type_of_plot == 'BAR1':
        columns_to_plot = st.selectbox("Select 1 column",all_columns,key='a' )
        columns_to_plot1 = st.selectbox("Select 2 column",[col for col in df.columns if col not in [columns_to_plot]], key='b' )
        columns_to_plot2 = st.selectbox("Select 3 column",[col for col in df.columns if col not in [columns_to_plot, columns_to_plot1]], key='c' )
    
        cje = df[columns_to_plot].tolist()
        other_var = df[columns_to_plot1].tolist()
        other_var1 = df[columns_to_plot2].tolist()
        bar = Bar()
        bar.add_xaxis(cje)
        bar.add_yaxis(columns_to_plot1, other_var)
        bar.add_yaxis(columns_to_plot2, other_var1)
        bar.set_global_opts(toolbox_opts=opts.ToolboxOpts(), legend_opts=opts.LegendOpts(is_show=False))
        bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='inside', font_size=12,
    formatter='{b}:{c}',font_style='italic', font_weight='bold', font_family='Microsoft YaHei'))
        bar.reversal_axis()
        bar.set_series_opts(label_opts=opts.LabelOpts(position="right"), markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(type_="min"),
                opts.MarkLineItem(type_="max"),
                opts.MarkLineItem(type_="average"),
            ]
        ),)
            #bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-Test Rendered Pictures"))
        # st.button("Generate Plot")
        return bar
        
    if type_of_plot == 'BAR2':
        
        columns_to_plot = st.selectbox("Select 1 column",all_columns,key='a' )
        columns_to_plot1 = st.selectbox("Select 2 column",[col for col in df.columns if col not in [columns_to_plot]], key='b' )
        cje = df[columns_to_plot].tolist()
        other_var = df[columns_to_plot1].tolist()
        bar = Bar()
        bar.add_xaxis(cje)
        bar.add_yaxis(columns_to_plot1, other_var, gap="0%")
       
        bar.set_global_opts(toolbox_opts=opts.ToolboxOpts(), 
                             legend_opts=opts.LegendOpts(is_show=False))
        bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='inside', font_size=12,
    formatter='{b}:{c}',font_style='italic', font_weight='bold', font_family='Microsoft YaHei')
        )
            
        bar.set_series_opts(
     
        markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(type_="min"),
                opts.MarkLineItem(type_="max"),
                opts.MarkLineItem(type_="average"),
            ]
        ),
    )
        return bar
    
    if type_of_plot == 'BAR3':
        columns_to_plot = st.selectbox("Select 1 column",all_columns,key='a' )
        columns_to_plot1 = st.selectbox("Select 2 column",[col for col in df.columns if col not in [columns_to_plot]], key='b' )
        columns_to_plot2 = st.selectbox("Select 3 column",[col for col in df.columns if col not in [columns_to_plot, columns_to_plot1]], key='c' )
        columns_to_plot3 = st.selectbox("Select 4 column",[col for col in df.columns if col not in [columns_to_plot, columns_to_plot1,columns_to_plot2]], key='d' )
        columns_to_plot4 = st.selectbox("Select 5 column",[col for col in df.columns if col not in [columns_to_plot, columns_to_plot1,columns_to_plot2,columns_to_plot3]], key='e' )
        cje = df[columns_to_plot].tolist()
        other_var1 = df[columns_to_plot1].tolist()
        other_var2 = df[columns_to_plot2].tolist()
        other_var3 = df[columns_to_plot3].tolist()
        other_var4 = df[columns_to_plot4].tolist()
        bar = Bar()
        bar.add_xaxis(cje)
        bar.add_yaxis(columns_to_plot1, other_var1)
        bar.add_yaxis(columns_to_plot2, other_var2)
        bar.add_yaxis(columns_to_plot3, other_var3)
        bar.add_yaxis(columns_to_plot4, other_var4)
      
        bar.reversal_axis()
        #bar.add_yaxis(columns_to_plot1, other_var, gap="0%")
       
        bar.set_global_opts(toolbox_opts=opts.ToolboxOpts(), 
                             xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=65)), 
                             brush_opts=opts.BrushOpts())
    #     bar.set_series_opts(label_opts=opts.LabelOpts( position='inside', font_size=8,
    # formatter='{b}:{c}',font_style='italic', font_weight='bold', font_family='Microsoft YaHei')
    #     )
        
        return bar
예제 #28
0
def barChart(df):
    type_of_plot = st.selectbox("Select Type of Plot",
                                ["BAR1", "BAR2", "BAR3", "BAR4", "BAR5"])
    all_columns = df.columns

    #st.success("Generating Customizable Plot of {} for {}".format(type_of_plot))

    if type_of_plot == 'BAR1':
        columns_to_plot = st.selectbox("Select 1 column", all_columns, key='a')
        columns_to_plot1 = st.selectbox("Select 2 column",
                                        all_columns,
                                        key='b')
        columns_to_plot2 = st.selectbox("Select 3 column",
                                        all_columns,
                                        key='c')

        cje = df[columns_to_plot].tolist()
        other_var = df[columns_to_plot1].tolist()
        other_var1 = df[columns_to_plot2].tolist()
        bar = Bar(init_opts=opts.InitOpts(width='900px', height='1200px'))
        bar.add_xaxis(cje)
        bar.add_yaxis(columns_to_plot1, other_var)
        bar.add_yaxis(columns_to_plot2, other_var1)
        bar.set_global_opts(toolbox_opts=opts.ToolboxOpts())
        bar.reversal_axis()
        bar.set_series_opts(
            label_opts=opts.LabelOpts(position="right"),
            markline_opts=opts.MarkLineOpts(data=[
                opts.MarkLineItem(type_="min", name="最小值"),
                opts.MarkLineItem(type_="max", name="最大值"),
                opts.MarkLineItem(type_="average", name="平均值"),
            ]),
        )
        #bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-Test Rendered Pictures"))
        # st.button("Generate Plot")
        return bar

    if type_of_plot == 'BAR2':

        columns_to_plot = st.selectbox("Select 1 column", all_columns, key='a')
        columns_to_plot1 = st.selectbox("Select 2 column",
                                        all_columns,
                                        key='b')
        cje = df[columns_to_plot].tolist()
        other_var = df[columns_to_plot1].tolist()
        bar = Bar(init_opts=opts.InitOpts(width='900px', height='1800px'))
        bar.add_xaxis(cje)
        bar.add_yaxis(columns_to_plot1, other_var, gap="0%")

        bar.set_global_opts(
            toolbox_opts=opts.ToolboxOpts(),
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=65)),
            brush_opts=opts.BrushOpts())

        bar.set_series_opts(markline_opts=opts.MarkLineOpts(data=[
            opts.MarkLineItem(type_="min", name="最小值"),
            opts.MarkLineItem(type_="max", name="最大值"),
            opts.MarkLineItem(type_="average", name="平均值"),
        ]), )
        return bar

    if type_of_plot == 'BAR3':
        columns_to_plot = st.selectbox("Select 1 column", all_columns, key='a')
        columns_to_plot1 = st.selectbox("Select 2 column",
                                        all_columns,
                                        key='b')
        columns_to_plot2 = st.selectbox("Select 3 column",
                                        all_columns,
                                        key='c')
        columns_to_plot3 = st.selectbox("Select 4 column",
                                        all_columns,
                                        key='d')
        columns_to_plot4 = st.selectbox("Select 5 column",
                                        all_columns,
                                        key='e')
        cje = df[columns_to_plot].tolist()
        other_var1 = df[columns_to_plot1].tolist()
        other_var2 = df[columns_to_plot2].tolist()
        other_var3 = df[columns_to_plot3].tolist()
        other_var4 = df[columns_to_plot4].tolist()
        bar = Bar(init_opts=opts.InitOpts(width='900px', height='1200px'))
        bar.add_xaxis(cje)
        bar.add_yaxis(columns_to_plot1, other_var1)
        bar.add_yaxis(columns_to_plot2, other_var2)
        bar.add_yaxis(columns_to_plot3, other_var3)
        bar.add_yaxis(columns_to_plot4, other_var4)

        bar.reversal_axis()
        #bar.add_yaxis(columns_to_plot1, other_var, gap="0%")

        bar.set_global_opts(
            toolbox_opts=opts.ToolboxOpts(),
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=65)),
            brush_opts=opts.BrushOpts())
        grid = Grid()
        grid.add(bar, grid_bottom="60%")
        return bar
예제 #29
0
# 添加一组纵轴数据
bar.add_yaxis(series_name='商家B', yaxis_data=[57, 134, 137, 129, 145, 60, 49])

# b、添加横轴数据
bar.add_xaxis(
    xaxis_data=['衬衫', '毛衣', '领带', '裤子', '风衣', '高跟鞋', '袜子'],  # 横轴数据
)

# 3、全局配置
# 可以通过 set_global_opts 来设置全局配置
bar.set_global_opts(
    # 标题配置项
    title_opts=opts.TitleOpts(
        title='柱状图绘制',  # 标题名称
    ))

# 4、系列配置
# 可以通过 set_series_opts 来设置全局配置项
bar.set_series_opts(
    # 标签配置项
    label_opts=opts.LabelOpts(
        is_show=True,  # 显示标签
        position='right',  # 设置标签位置
    ))

# 注意:翻转坐标系
bar.reversal_axis()

# 5、生成图像
bar.render('./html/柱状图绘制.html')
예제 #30
0
def find_difference_render(data,X,query,table_path,answer):
    colorList = ['#f36c6c', '#e6cf4e', '#20d180', '#0093ff',"#ca8622","#726930",]
    if len(data)==2:
        bar1=Bar()
        bar1.add_xaxis(X[1])
        bar1.add_yaxis("",data[0][1],label_opts=opts.LabelOpts(position="insideLeft"))
        bar1.reversal_axis()
        bar1.set_global_opts(
            datazoom_opts=[opts.DataZoomOpts(range_start=10,range_end=90,orient="vertical"), opts.DataZoomOpts(type_="inside")],
            xaxis_opts=opts.AxisOpts(
                position="top"
            ),
            yaxis_opts=opts.AxisOpts(
                is_inverse=True
            ),
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",

                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n' +"\n"+ 'A:' + ' ' + answer],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        bar2=Bar()
        bar2.add_xaxis(X[1])
        bar2.add_yaxis("",data[1][1],label_opts=opts.LabelOpts(position="insideRight"))
        bar2.reversal_axis()
        bar2.set_global_opts(
            datazoom_opts=[opts.DataZoomOpts(range_start=10, range_end=90, orient="vertical"),
                           opts.DataZoomOpts(type_="inside")],
            xaxis_opts=opts.AxisOpts(
                position="top",
                is_inverse=True
            ),
            yaxis_opts=opts.AxisOpts(
                is_inverse=True,
                position="right"
            ),
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",

                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n' +"\n"+ 'A:' + ' ' + answer],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        grid1 = Grid(init_opts=opts.InitOpts(
            width="100%",
            height="100%",
            renderer=globals.RenderType.SVG, ) )
        grid1.add(bar1, grid_opts=opts.GridOpts(
            pos_left="60%",pos_bottom="30%"
        ))
        grid1.add(bar2, grid_opts=opts.GridOpts(
            pos_right="60%",pos_bottom="30%"
        ))
        grid1.render("a.html")
        option1 = grid1.dump_options_with_quotes()
        option1 = json.loads(option1)
        lable=[]
        for i in range(len(X[1])):
            lable.append(opts.RadarIndicatorItem(name=X[1][i]))
        # r_data=[]
        # for record in data:
        #     r_data.append(record[1])
        radar=Radar(init_opts=opts.InitOpts(bg_color="#CCCCCC"))
        radar.add_schema(
            schema=lable,
            splitarea_opt=opts.SplitAreaOpts(
               is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
             ),
            textstyle_opts=opts.TextStyleOpts(color="#fff"),
        )
        for i in range(len(data)):
            radar.add(
                series_name=data[i][0],
                label_opts=opts.LabelOpts(is_show=False),
                data=[data[i][1]],
                linestyle_opts=opts.LineStyleOpts(
                    color=colorList[i],
                    width=3

                )
            )
        radar.set_global_opts(
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",
                    z=100,
                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n'+"\n" + 'A:' + ' ' + answer],
                    font="10px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        grid2 = Grid(init_opts=opts.InitOpts(
            width="100%",
            height="100%",
            renderer=globals.RenderType.SVG, ))
        grid2.add(radar, grid_opts={'left': '20%', 'bottom': '40%',"top":"1%"})
        option2 = grid2.dump_options_with_quotes()
        option2 = json.loads(option2)
        bar3=Bar()
        bar3.add_xaxis(X[1])
        for i in range(len(data)):
            bar3.add_yaxis(data[i][0],data[i][1],label_opts=opts.LabelOpts(is_show=False))
        bar3.set_global_opts(
            datazoom_opts=[opts.DataZoomOpts(range_start=10, range_end=90),
                           opts.DataZoomOpts(type_="inside")],
            xaxis_opts=opts.AxisOpts(
                name=X[0]
            ),
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",
                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n' +"\n"+ 'A:' + ' ' + answer],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        grid3 = Grid(init_opts=opts.InitOpts(
            width="100%",
            height="100%",
            renderer=globals.RenderType.SVG, ))
        grid3.add(bar3, grid_opts={'left': '20%', 'bottom': '30%'})
        option3 = grid3.dump_options_with_quotes()
        option3 = json.loads(option3)
        option = {"option": [option1,option2,option3], "query": query}
        return option

    elif len(data)>2 and len(data[0][1])>1:
        lable=[]
        for i in range(len(X[1])):
            lable.append(opts.RadarIndicatorItem(name=X[1][i]))
        # r_data=[]
        # for record in data:
        #     r_data.append(record[1])
        radar=Radar(init_opts=opts.InitOpts(bg_color="#CCCCCC"))
        radar.add_schema(
            schema=lable,
            splitarea_opt=opts.SplitAreaOpts(
               is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
             ),
            textstyle_opts=opts.TextStyleOpts(color="#fff"),
        )
        radar.set_global_opts(
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",

                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n' +"\n"+ 'A:' + ' ' + answer],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        for i in range(len(data)):
            radar.add(
                series_name=data[i][0],
                label_opts=opts.LabelOpts(is_show=False),
                data=[data[i][1]],
                linestyle_opts=opts.LineStyleOpts(
                    color=colorList[i],
                    width=3

                )
            )

        grid1 = Grid(init_opts=opts.InitOpts(
        width="100%",
        height="100%",
        renderer=globals.RenderType.SVG, ))
        grid1.add(radar, grid_opts={'left': '20%', 'bottom': '30%'})
        option1 = grid1.dump_options_with_quotes()
        option1 = json.loads(option1)
        bar = Bar()
        bar.add_xaxis(X[1])
        for i in range(len(data)):
          bar.add_yaxis(data[i][0], data[i][1],label_opts=opts.LabelOpts(is_show=False))
        bar.set_global_opts(
            datazoom_opts=[opts.DataZoomOpts(range_start=10, range_end=90),
                           opts.DataZoomOpts(type_="inside")],
          xaxis_opts=opts.AxisOpts(
            name=X[0]
          ),
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",

                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n' +"\n"+ 'A:' + ' ' + answer],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        grid2 = Grid(init_opts=opts.InitOpts(
        width="100%",
        height="100%",
        renderer=globals.RenderType.SVG, ))
        grid2.add(bar, grid_opts={'left': '20%', 'bottom': '30%'})
        option2 = grid2.dump_options_with_quotes()
        option2 = json.loads(option2)
        option = {"option": [option1,option2], "query": query}
        return option
    elif len(data)>2 and len(data[0][1])==1:
        bar = Bar()
        bar.add_xaxis(X[1])
        for i in range(len(data)):
          bar.add_yaxis(data[i][0], data[i][1],label_opts=opts.LabelOpts(is_show=False))
        bar.set_global_opts(
            datazoom_opts=[opts.DataZoomOpts(range_start=10, range_end=90),
                           opts.DataZoomOpts(type_="inside")],
          xaxis_opts=opts.AxisOpts(
            name=X[0]
          ),
            graphic_opts=[opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",
                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=['\n' + "Q:" + ' ' + query + '\n' +"\n"+ 'A:' + ' ' + answer],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333"
                    )
                )
            )]
        )
        grid2 = Grid(init_opts=opts.InitOpts(
        width="100%",
        height="100%",
        renderer=globals.RenderType.SVG, ))
        grid2.add(bar, grid_opts={'left': '20%', 'bottom': '34%'})
        option2 = grid2.dump_options_with_quotes()
        option2 = json.loads(option2)
        option = {"option": [option2], "query": query}
        return option