コード例 #1
0
ファイル: test_timeline.py プロジェクト: Jesszen/pyecharts
def test_timeline_map():
    timeline = Timeline(timeline_bottom=0)
    value = [155, 10, 66, 78, 33, 80, 190, 53, 49.6]
    attr = ["福建", "山东", "北京", "上海", "甘肃", "新疆", "河南", "广西", "西藏"]
    map = Map("Map 结合 VisualMap 示例", width=1200, height=600)
    map.add(
        "",
        attr,
        value,
        maptype="china",
        is_visualmap=True,
        visual_text_color="#000",
        visual_top="30%",
    )
    timeline.add(map, "test1")
    value = [155, 10, 66, 78, 33]
    attr = ["福建", "山东", "北京", "上海", "甘肃"]
    map = Map("Map 结合 VisualMap 示例", width=1200, height=600)
    map.add(
        "",
        attr,
        value,
        maptype="china",
        is_visualmap=True,
        visual_text_color="#000",
        visual_top="30%",
    )
    timeline.add(map, "test2")
    assert len(timeline.options.get("baseOption").get("series")) == 2
    timeline.render()
コード例 #2
0
def test_timeline_pie():
    style = Style()
    pie_style = style.add(is_label_show=True,
                          radius=[30, 55],
                          rosetype="radius")
    pie_1 = Pie("2012 年销量比例", "数据纯属虚构")
    pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_2 = Pie("2013 年销量比例", "数据纯属虚构")
    pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_3 = Pie("2014 年销量比例", "数据纯属虚构")
    pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_4 = Pie("2015 年销量比例", "数据纯属虚构")
    pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_5 = Pie("2016 年销量比例", "数据纯属虚构")
    pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    timeline = Timeline(is_auto_play=True,
                        timeline_bottom=0,
                        width=1200,
                        height=600)
    timeline.add(pie_1, '2012 年')
    timeline.add(pie_2, '2013 年')
    timeline.add(pie_3, '2014 年')
    timeline.add(pie_4, '2015 年')
    timeline.add(pie_5, '2016 年')
    timeline.render()
コード例 #3
0
ファイル: test_timeline.py プロジェクト: Jesszen/pyecharts
def test_timeline_pie():
    style = Style()
    pie_style = style.add(
        is_label_show=True, radius=[30, 55], rosetype="radius"
    )
    pie_1 = Pie("2012 年销量比例", "数据纯属虚构")
    pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_2 = Pie("2013 年销量比例", "数据纯属虚构")
    pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_3 = Pie("2014 年销量比例", "数据纯属虚构")
    pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_4 = Pie("2015 年销量比例", "数据纯属虚构")
    pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_5 = Pie("2016 年销量比例", "数据纯属虚构")
    pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    timeline = Timeline(
        is_auto_play=True, timeline_bottom=0, width=1200, height=600
    )
    timeline.add(pie_1, "2012 年")
    timeline.add(pie_2, "2013 年")
    timeline.add(pie_3, "2014 年")
    timeline.add(pie_4, "2015 年")
    timeline.add(pie_5, "2016 年")
    assert len(timeline.options.get("baseOption").get("series")) == 0
    timeline.render()
コード例 #4
0
ファイル: test_timeline.py プロジェクト: chumingke/pyecharts
def test_timeline_pie():
    style = Style()
    pie_style = style.add(
        is_label_show=True,
        radius=[30, 55],
        rosetype="radius"
    )
    pie_1 = Pie("2012 年销量比例", "数据纯属虚构")
    pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_2 = Pie("2013 年销量比例", "数据纯属虚构")
    pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_3 = Pie("2014 年销量比例", "数据纯属虚构")
    pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_4 = Pie("2015 年销量比例", "数据纯属虚构")
    pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_5 = Pie("2016 年销量比例", "数据纯属虚构")
    pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    timeline = Timeline(is_auto_play=True, timeline_bottom=0,
                        width=1200, height=600)
    timeline.add(pie_1, '2012 年')
    timeline.add(pie_2, '2013 年')
    timeline.add(pie_3, '2014 年')
    timeline.add(pie_4, '2015 年')
    timeline.add(pie_5, '2016 年')
    timeline.render()
コード例 #5
0
def test_timeline_pie():
    style = Style()
    pie_style = style.add(is_label_show=True,
                          radius=[30, 55],
                          rosetype="radius")
    pie_1 = Pie("2012 年销量比例", "数据纯属虚构")
    pie_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_2 = Pie("2013 年销量比例", "数据纯属虚构")
    pie_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_3 = Pie("2014 年销量比例", "数据纯属虚构")
    pie_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_4 = Pie("2015 年销量比例", "数据纯属虚构")
    pie_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    pie_5 = Pie("2016 年销量比例", "数据纯属虚构")
    pie_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)], **pie_style)

    timeline = Timeline(is_auto_play=True,
                        timeline_bottom=0,
                        width=1200,
                        height=600)
    timeline.add(pie_1, "2012 年")
    timeline.add(pie_2, "2013 年")
    timeline.add(pie_3, "2014 年")
    timeline.add(pie_4, "2015 年")
    timeline.add(pie_5, "2016 年")
    assert len(timeline._option.get("baseOption").get("series")) == 0
    timeline.render()
コード例 #6
0
def test_timeline_map():
    timeline = Timeline(timeline_bottom=0)
    value = [155, 10, 66, 78, 33, 80, 190, 53, 49.6]
    attr = ["福建", "山东", "北京", "上海", "甘肃", "新疆", "河南", "广西", "西藏"]
    map = Map("Map 结合 VisualMap 示例", width=1200, height=600)
    map.add(
        "",
        attr,
        value,
        maptype="china",
        is_visualmap=True,
        visual_text_color="#000",
        visual_top="30%",
    )
    timeline.add(map, "test1")
    value = [155, 10, 66, 78, 33]
    attr = ["福建", "山东", "北京", "上海", "甘肃"]
    map = Map("Map 结合 VisualMap 示例", width=1200, height=600)
    map.add(
        "",
        attr,
        value,
        maptype="china",
        is_visualmap=True,
        visual_text_color="#000",
        visual_top="30%",
    )
    timeline.add(map, "test2")
    assert len(timeline._option.get("baseOption").get("series")) == 2
    timeline.render()
コード例 #7
0
def ShowNumWithYear(df):
    # show bus num in different year at different cities
    years = list(set(df['year']))
    years.sort()
    cities = []
    values = []
    total_num = 0
    geos = []  # store the geo every year
    timeline = Timeline(width=1500,height=800,is_auto_play=True, timeline_bottom=-10,timeline_symbol_size=20,\
        timeline_play_interval = 800,timeline_left=20,timeline_right=100 , is_timeline_show = False )
    for index in range(len(years)):
        df_temp = df[df['year'] == years[index]]
        cities = cities + list(df_temp['city'])
        values = values + list(df_temp['num'])
        total_num = sum(values)
        geos.append(Geo( str(years[index]) + " , Fist level title" , title_top = "10%" , title_text_size=50 , subtitle = "second level title" , \
            subtitle_text_size = 23 , subtitle_color="white", \
            title_color="red", title_pos="center", width=1200, height=600, \
            background_color='#404a59'))
        # type="effectScatter", is_random=True, effect_scale=5  使点具有发散性
        geos[index].add("数量", cities, values, type="effectScatter", maptype='china' , is_random=True, effect_scale=3,  is_selected = True,is_toolbox_show = True ,is_more_utils =True,\
            visual_text_color="#fff", symbol_size=10, is_label_show = True ,  legend_orient = 'left' ,is_legend_show = False, legend_top = 'bottom' , label_formatter = '{b}' , \
            is_visualmap=True, is_roam=True , label_text_color="#00FF00" , is_piecewise=True, label_text_size = 7,visual_range=[1, 300] , \
            geo_cities_coords = {'柯桥': [120.443 , 30.0822] ,}  , \
            pieces=[
                {"min":0.1, "max": 500 , "label": "0-500"},
                {"min": 500, "max": 1000 , "label": "501-1000"},
                {"min": 1001, "max": 2000 , "label": "1001-2000"},
                {"min":2001, "max": 5000, "label": "2001-5000"},
                {"min":5001, "max": 100000, "label": ">5000"}, ] )
        geos[index].show_config()
        geos[index].render("数量.html")
        #   时间轴定义
        timeline.add(geos[index], years[index])
    timeline.render('redult.html')
コード例 #8
0
def show_ruanke_best(begin_year,end_year):
    '''
    @author: Hong wentao
             用于展示每一个学科的学校的排名可视化,使用的是软科最好大学排名的数据
    '''
    path=data_path+"ruanke_best_subject/"
    ruanke_html_path=html_path+"ruanke/"
    isExists=os.path.exists(ruanke_html_path)
    if not isExists:
        os.makedirs(ruanke_html_path)
    first_names=os.listdir(path)
    for first_name in first_names:
        first_data_path=path+first_name+"/"
        first_html_path=ruanke_html_path+first_name+"/"
        isExists=os.path.exists(first_html_path)
        if not isExists:
            os.makedirs(first_html_path)
        second_names=os.listdir(first_data_path)
        for second_name in second_names:
            second_data_path=first_data_path+second_name+"/"
            second_html_path=first_html_path+second_name+"/"
            isExists=os.path.exists(second_html_path)
            if not isExists:
                os.makedirs(second_html_path)
            data=deal_ruanke.every_subject_ruanke(first_name,second_name)    
            timeline = Timeline(is_auto_play=False, timeline_bottom=0,width=stand_width)
            for i in range(begin_year,end_year+1):
                bar = Bar(second_name+str(i)+"年大学排名数据")
                try:
                    want_data=data[i]
                    nan='空白区域说明该学校当年无该数据'
                    final_data=[]
                    have_name=[]
                    before_median=[]
                    for x in want_data:
                        have_name.append(x[2])
                    for name in university_name:
                        if name not in have_name:
                            final_data.append("nan")
                        else:
                            for x in want_data:
                                if x[2]==name:    
                                    final_data.append(x[0])
                                    before_median.append(x[0])
                                    break;
                    a=np.array(before_median).astype("int")
                    median=np.median(a).astype("int")
                    bar.add("排名  "+nan, university_name,final_data, is_label_show=True,is_stack=True,xaxis_interval=0,xaxis_name_size=15,xaxis_rotate=0,yaxis_name_rotate=0,xaxis_name_pos="end", xaxis_name="学校名",yaxis_name="排名",yaxis_name_gap=10,yaxis_name_pos="end",mark_point=["max","min"],mark_line_raw=[{"yAxis": median,"name":"中位数","lineStyle": {
                        "color": 'black'
                        }}])
                    timeline.add(bar, str(i)+'年') 
                    timeline.render(second_html_path+second_name+".html") 
                except Exception:
                    print(first_name+" "+second_name+str(i)+"没有")
                    continue    
            timeline.render(second_html_path+second_name+".html")  
コード例 #9
0
def time_line():
    timeline = Timeline(page_title="Time Line")
    stack_bar, line = StackBar.stack_bar()
    tree_chart = TreeChart.tree_chart()
    stack_bar_chart = StackBarChart.stack_bar_chart2()
    stack_line = StackChart.starck_line_chart()

    timeline.add(stack_line, time_point=7)
    timeline.add(stack_bar_chart, time_point=8)
    timeline.add(tree_chart, time_point=6)
    timeline.add(stack_bar,time_point=2)
    timeline.add(line, time_point=3)
    timeline.render("timeline.html")
コード例 #10
0
def geographical_location_GDP_ratio_distribution():
    data = pd.read_excel("./data/car_sales_data.xlsx", sheet_name=u"人均GDP", encoding='utf-8')
    data.columns = [str(col).split('-')[0] for col in data.columns]

    float_cols = [str(year) for year in range(1998, 2018)]
    not_replace = [
        u'池州市', u'宣城市', u'眉山市', u'达州市', u'庆阳市',
        u'广安市', u'贺州市', u'来宾市', u'崇左市', u'临沧市',
        u'固原市', u'中卫市', u'丽江市'
    ]
    data['city_name'] = data['city_name'].apply(lambda xx: xx.replace(u'市', '') if xx not in not_replace else xx)
    city_none = [u'黔西南布依族苗族自治州', u'乌兰察布', u'巴音郭楞蒙古自治州(库尔勒)']
    data = data[~data['city_name'].isin(city_none)]
    data[float_cols] = data[float_cols].fillna(0).applymap(lambda xx: round(xx, 2) if xx else 0)
    cols_show = ['city_name'] + float_cols
    data = data[cols_show]
    data = calc_ratio_percent(data)
    data[range(1999, 2018)] = data[range(1999, 2018)].applymap(lambda xx: round(xx * 100, 2))
    data.to_excel('./car_sales_visualization/GDP_ratio_distribution.xlsx')

    timeline = Timeline(is_auto_play=False, timeline_bottom=1250, width=2480, height=1330)

    for year in range(1999, 2018):
        dataset = [(city, sales) for city, sales in data[['city_name'] + [year]].values]

        geo = Geo(
            "%s - Car Sales Num Ratio Distribution" % year,
            "",
            title_pos="center",
            title_color="black",
            width=2480,
            height=1330,
            background_color='#ffffff'
        )
        attr, value = geo.cast(dataset)
        geo.add(
            "",
            attr,
            value,
            type="effectScatter",
            is_visualmap=True,
            maptype='china',
            visual_range=[-100.0, 100.0],
            visual_text_color="black",
            effect_scale=5,
            symbol_size=5
        )

        timeline.add(geo, year)

    timeline.render('./car_sales_visualization/GDP_ratio_distribution.html')
コード例 #11
0
def test_timeline_bar_line():
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line = Line()
    line.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_0 = Overlap()
    overlap_0.add(bar)
    overlap_0.add(line)

    bar_1 = Bar("2 月份数据", "数据纯属虚构")
    bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_1 = Line()
    line_1.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_1 = Overlap()
    overlap_1.add(bar_1)
    overlap_1.add(line_1)

    bar_2 = Bar("3 月份数据", "数据纯属虚构")
    bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_2 = Line()
    line_2.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_2 = Overlap()
    overlap_2.add(bar_2)
    overlap_2.add(line_2)

    bar_3 = Bar("4 月份数据", "数据纯属虚构")
    bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_3 = Line()
    line_3.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_3 = Overlap()
    overlap_3.add(bar_3)
    overlap_3.add(line_3)

    bar_4 = Bar("5 月份数据", "数据纯属虚构")
    bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_4 = Line()
    line_4.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_4 = Overlap()
    overlap_4.add(bar_4)
    overlap_4.add(line_4)

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap_0, '1 月')
    timeline.add(overlap_1, '2 月')
    timeline.add(overlap_2, '3 月')
    timeline.add(overlap_3, '4 月')
    timeline.add(overlap_4, '5 月')
    assert len(timeline._option.get("baseOption").get("series")) == 10
    timeline.render()
コード例 #12
0
ファイル: test_timeline.py プロジェクト: Jesszen/pyecharts
def test_timeline_bar_line():
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line = Line()
    line.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_0 = Overlap()
    overlap_0.add(bar)
    overlap_0.add(line)

    bar_1 = Bar("2 月份数据", "数据纯属虚构")
    bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_1 = Line()
    line_1.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_1 = Overlap()
    overlap_1.add(bar_1)
    overlap_1.add(line_1)

    bar_2 = Bar("3 月份数据", "数据纯属虚构")
    bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_2 = Line()
    line_2.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_2 = Overlap()
    overlap_2.add(bar_2)
    overlap_2.add(line_2)

    bar_3 = Bar("4 月份数据", "数据纯属虚构")
    bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_3 = Line()
    line_3.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_3 = Overlap()
    overlap_3.add(bar_3)
    overlap_3.add(line_3)

    bar_4 = Bar("5 月份数据", "数据纯属虚构")
    bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_4 = Line()
    line_4.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_4 = Overlap()
    overlap_4.add(bar_4)
    overlap_4.add(line_4)

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap_0, "1 月")
    timeline.add(overlap_1, "2 月")
    timeline.add(overlap_2, "3 月")
    timeline.add(overlap_3, "4 月")
    timeline.add(overlap_4, "5 月")
    timeline.render()
コード例 #13
0
def test_timeline_bar_line():
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line = Line()
    line.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_0 = Overlap()
    overlap_0.add(bar)
    overlap_0.add(line)

    bar_1 = Bar("2 月份数据", "数据纯属虚构")
    bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_1 = Line()
    line_1.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_1 = Overlap()
    overlap_1.add(bar_1)
    overlap_1.add(line_1)

    bar_2 = Bar("3 月份数据", "数据纯属虚构")
    bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_2 = Line()
    line_2.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_2 = Overlap()
    overlap_2.add(bar_2)
    overlap_2.add(line_2)

    bar_3 = Bar("4 月份数据", "数据纯属虚构")
    bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_3 = Line()
    line_3.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_3 = Overlap()
    overlap_3.add(bar_3)
    overlap_3.add(line_3)

    bar_4 = Bar("5 月份数据", "数据纯属虚构")
    bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_4 = Line()
    line_4.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_4 = Overlap()
    overlap_4.add(bar_4)
    overlap_4.add(line_4)

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap_0, "1 月")
    timeline.add(overlap_1, "2 月")
    timeline.add(overlap_2, "3 月")
    timeline.add(overlap_3, "4 月")
    timeline.add(overlap_4, "5 月")
    timeline.render()
コード例 #14
0
def geographical_location_ratio_distribution():
    data = pd.read_csv("./data/car_sales_volume_data.csv", encoding='utf-8')
    data = data[data['city'].str.len() > 1]

    data = calc_ratio_percent(data)
    data[range(1998, 2019)] = data[range(1998, 2019)].applymap(lambda xx: round(xx * 100, 4))
    cols_show = ['city'] + range(1998, 2019)
    data = data[cols_show]

    city_none = [
        u'三沙', u'中卫', u'临沧', u'丽江',
        u'克孜勒苏柯尔克孜自治州', u'其它',
        u'固原', u'新疆自治区直辖', u'普洱',
        u'河南省省直辖', u'海南省省直辖', u'湖北省省直辖'
    ]
    data = data[~data['city'].isin(city_none)]
    data.to_excel('./car_sales_visualization/car_sales_num_ratio.xlsx')

    timeline = Timeline(is_auto_play=False, timeline_bottom=1250, width=2480, height=1330)
    for year in range(1998, 2019):
        dataset = [(city, sales) for city, sales in data[['city'] + [year]].values]

        geo = Geo(
            "%s - Car Sales Num Ratio Distribution" % year,
            "",
            title_pos="center",
            title_color="black",
            width=2480,
            height=1330,
            background_color='#ffffff'
        )
        attr, value = geo.cast(dataset)
        geo.add(
            "",
            attr,
            value,
            type="effectScatter",
            is_visualmap=True,
            maptype='china',
            visual_range=[-100, 100],
            visual_text_color="black",
            effect_scale=5,
            symbol_size=5
        )

        timeline.add(geo, year)

    timeline.render('./car_sales_visualization/car_sales_num_ratio.html')
コード例 #15
0
ファイル: ProjectReport.py プロジェクト: GRUNMI/AutoDot
def get_html_project_report(project_name, type=0):
    mylogger = common.LogOutput.Log().get_logger()
    mylogger.info(
        "------------------------------------------------------------------")
    mylogger.info("当前运行文件:{}".format(__file__))
    try:
        project_run_num = get_project_run_num(project_name, type)
        # num = [successNum, failedNum, noRunNum]
        num = [project_run_num[0], project_run_num[1], project_run_num[2]]
        attr = ["成功用例", "失败用例", "不执行用例"]
        bar = Bar(project_name, "用例执行结果")
        bar.add("", attr, num, is_more_utils=True)
        bar.show_config()

        pie_1 = Pie(project_name, "用例执行结果")
        pie_1.add(project_name,
                  attr,
                  num,
                  is_label_show=True,
                  radius=[30, 55],
                  rosetype='radius')

        timeline = Timeline(is_auto_play=True, timeline_bottom=0)
        timeline.add(bar, '树形图')
        timeline.add(pie_1, '饼形图')

        PATH = lambda P: os.path.abspath(
            os.path.join(os.path.dirname(__file__), P))
        html_dirname = PATH(
            "../report") + "\\" + project_name + "\\" + "htmlReport\\"

        # 判断是否存在case目录,没有,则创建
        if not os.path.exists(html_dirname):
            os.mkdir(html_dirname)
            mylogger.info("生成用例目录路径:{}".format(html_dirname))
        if type == 0:
            html_report_name = time.strftime('%Y-%m-%d %H-%M-%S') + '.html'
        elif type == 1:
            html_report_name = 'settingReport' + time.strftime(
                '%Y-%m-%d %H-%M-%S') + '.html'
        htmlReportPath = html_dirname + html_report_name
        timeline.render(htmlReportPath)
        return 'success'
    except TypeError as e:
        return 'caseEmpty', e
コード例 #16
0
def test_timeline_bar():
    bar_1 = Bar("2012 年销量", "数据纯属虚构")
    bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_2 = Bar("2013 年销量", "数据纯属虚构")
    bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_3 = Bar("2014 年销量", "数据纯属虚构")
    bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_4 = Bar("2015 年销量", "数据纯属虚构")
    bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_5 = Bar("2016 年销量", "数据纯属虚构")
    bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add(
        "冬季",
        CLOTHES,
        [randint(10, 100) for _ in range(6)],
        is_legend_show=True,
    )

    timeline = Timeline(is_auto_play=True, timeline_bottom=0)
    timeline.add(bar_1, "2012 年")
    timeline.add(bar_2, "2013 年")
    timeline.add(bar_3, "2014 年")
    timeline.add(bar_4, "2015 年")
    timeline.add(bar_5, "2016 年")
    assert len(timeline._option.get("baseOption").get("series")) == 0
    timeline.render()
コード例 #17
0
ファイル: test_timeline.py プロジェクト: Jesszen/pyecharts
def test_timeline_bar():
    bar_1 = Bar("2012 年销量", "数据纯属虚构")
    bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_2 = Bar("2013 年销量", "数据纯属虚构")
    bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_3 = Bar("2014 年销量", "数据纯属虚构")
    bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_4 = Bar("2015 年销量", "数据纯属虚构")
    bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_5 = Bar("2016 年销量", "数据纯属虚构")
    bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add(
        "冬季",
        CLOTHES,
        [randint(10, 100) for _ in range(6)],
        is_legend_show=True,
    )

    timeline = Timeline(is_auto_play=True, timeline_bottom=0)
    timeline.add(bar_1, "2012 年")
    timeline.add(bar_2, "2013 年")
    timeline.add(bar_3, "2014 年")
    timeline.add(bar_4, "2015 年")
    timeline.add(bar_5, "2016 年")
    assert len(timeline.options.get("baseOption").get("series")) == 0
    timeline.render()
コード例 #18
0
def geographical_location_amount_distribution():
    data = pd.read_csv("./data/car_sales_volume_data.csv", encoding='utf-8')
    data = data[data['city'].str.len() > 1]

    city_none = [
        u'三沙', u'中卫', u'临沧', u'丽江',
        u'克孜勒苏柯尔克孜自治州', u'其它',
        u'固原', u'新疆自治区直辖', u'普洱',
        u'河南省省直辖', u'海南省省直辖', u'湖北省省直辖'
    ]
    data = data[~data['city'].isin(city_none)]
    int_cols = [str(col) for col in range(1998, 2019)]
    data[int_cols] = data[int_cols].applymap(lambda xx: float(xx))

    timeline = Timeline(is_auto_play=False, timeline_bottom=1250, width=2480, height=1330)
    for year in range(1998, 2019):
        dataset = [(city, sales) for city, sales in data[('city %s' % year).split()].values]
        print dataset

        geo = Geo(
            "%s - Car Sales Num Amount Distribution" % year,
            "",
            title_pos="center",
            title_color="black",
            width=2700,
            height=1340,
            background_color='#ffffff'
        )
        attr, value = geo.cast(dataset)
        geo.add(
            "",
            attr,
            value,
            maptype='china',
            visual_range=[0, 300000],
            visual_text_color="black",
            type="heatmap",
            is_visualmap=True,
            effect_scale=5,
            symbol_size=5,
        )
        timeline.add(geo, year)

    timeline.render('./car_sales_visualization/car_sales_num_amount.html')
コード例 #19
0
ファイル: data_map.py プロジェクト: zhangwt-per/GeoProject
def bar_map():
    kwargs = dict(
        label_text_color=None,
        is_label_show=True,
        legend_orient='vertical',
        legend_pos='right',
        legend_top='center',
        legend_selectedmode='single',
        legend_text_size=18,
        label_text_size=18,
        label_emphasis_textsize=18,
        xaxis_name_size=18,
        xaxis_label_textsize=18,
        xaxis_margin=5,
        xaxis_line_width=2,
        yaxis_name_size=18,
        yaxis_label_textsize=18,
        bar_category_gap=25,
        yaxis_line_width=2,
        is_splitline_show=False,
        is_xaxis_boundarygap=True,
        is_toolbox_show=False,
    )
    timeline = Timeline(timeline_bottom=0,
                        width=1400,
                        height=700,
                        timeline_symbol_size=10)
    for year in value_base.current_years:
        bar = Bar('村镇对比图',
                  title_pos='center',
                  title_text_size=30,
                  title_top=10)
        for index in value_base.current_indexs:
            data = []
            for i in value_base.current_areas:
                for veti_data in value_base.veti_data_dict[year]:
                    if veti_data[0] == i:
                        data.append(
                            veti_data[value_base.index_num_dict[index]])
            bar.add(index, value_base.current_areas, data, **kwargs)
        timeline.add(bar, year)
    result = str(value_base.output_dir + u"村镇对比.html")
    timeline.render(result)
コード例 #20
0
def plot_bar_graph():
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    bar_1 = Bar("2012 年销量", "数据纯属虚构")
    bar_1.add("春季", attr, [randint(10, 100) for _ in range(6)])
    bar_1.add("夏季", attr, [randint(10, 100) for _ in range(6)])
    bar_1.add("秋季", attr, [randint(10, 100) for _ in range(6)])
    bar_1.add("冬季", attr, [randint(10, 100) for _ in range(6)])

    bar_2 = Bar("2013 年销量", "数据纯属虚构")
    bar_2.add("春季", attr, [randint(10, 100) for _ in range(6)])
    bar_2.add("夏季", attr, [randint(10, 100) for _ in range(6)])
    bar_2.add("秋季", attr, [randint(10, 100) for _ in range(6)])
    bar_2.add("冬季", attr, [randint(10, 100) for _ in range(6)])

    bar_3 = Bar("2014 年销量", "数据纯属虚构")
    bar_3.add("春季", attr, [randint(10, 100) for _ in range(6)])
    bar_3.add("夏季", attr, [randint(10, 100) for _ in range(6)])
    bar_3.add("秋季", attr, [randint(10, 100) for _ in range(6)])
    bar_3.add("冬季", attr, [randint(10, 100) for _ in range(6)])

    bar_4 = Bar("2015 年销量", "数据纯属虚构")
    bar_4.add("春季", attr, [randint(10, 100) for _ in range(6)])
    bar_4.add("夏季", attr, [randint(10, 100) for _ in range(6)])
    bar_4.add("秋季", attr, [randint(10, 100) for _ in range(6)])
    bar_4.add("冬季", attr, [randint(10, 100) for _ in range(6)])

    bar_5 = Bar("2016 年销量", "数据纯属虚构")
    bar_5.add("春季", attr, [randint(10, 100) for _ in range(6)])
    bar_5.add("夏季", attr, [randint(10, 100) for _ in range(6)])
    bar_5.add("秋季", attr, [randint(10, 100) for _ in range(6)])
    bar_5.add("冬季",
              attr, [randint(10, 100) for _ in range(6)],
              is_legend_show=True)

    timeline = Timeline(page_title=u'销量分析',
                        is_auto_play=False,
                        timeline_bottom=0)
    timeline.add(bar_1, '2012 年')
    timeline.add(bar_2, '2013 年')
    timeline.add(bar_3, '2014 年')
    timeline.add(bar_4, '2015 年')
    timeline.add(bar_5, '2016 年')
    timeline.render(FILE_DIR + 'bar_graph.html')
コード例 #21
0
ファイル: data_map.py プロジェクト: zhangwt-per/GeoProject
def radar_map():
    kwargs = dict(label_text_color=None,
                  is_label_show=True,
                  legend_orient='vertical',
                  legend_pos='right',
                  legend_top='center',
                  legend_text_size=18,
                  label_text_size=18,
                  label_emphasis_textsize=18,
                  xaxis_name_size=18,
                  xaxis_label_textsize=18,
                  xaxis_margin=5,
                  xaxis_line_width=2,
                  yaxis_name_size=18,
                  yaxis_label_textsize=18,
                  yaxis_line_width=2,
                  is_splitline_show=False,
                  is_xaxis_boundarygap=True,
                  is_toolbox_show=False,
                  line_width=3)
    timeline = Timeline(timeline_bottom=0,
                        width=1400,
                        height=700,
                        timeline_symbol_size=10)
    for year in value_base.current_years:
        radar_map = Radar('雷达图',
                          title_pos='center',
                          title_text_size=30,
                          title_top=10)
        for area in value_base.current_areas:
            data = [[]]
            for index in value_base.current_indexs:
                for veti_data in value_base.veti_data_dict[year]:
                    if veti_data[0] == area:
                        data[0].append(
                            round(veti_data[value_base.index_num_dict[index]],
                                  2))
            radar_map.set_radar_component(schema=value_base.radar_schema)
            radar_map.add(area, data, **kwargs)
        timeline.add(radar_map, year)
    result = str(value_base.output_dir + u"雷达图.html")
    timeline.render(result)
コード例 #22
0
def plot_map(df):
    # maptype='china' 只显示全国直辖市和省级
    # 数据只能是省名和直辖市的名称
    # province_distribution = {'青岛': 22, '龙口': 37.56, '河北': 21, '辽宁': 12, '江西': 6, '上海': 20, '安徽': 10, '江苏': 16, '湖南': 9, '浙江': 13, '海南': 2, '广东': 22, '湖北': 8, '黑龙江': 11, '澳门': 1, '陕西': 11, '四川': 7, '内蒙古': 3, '重庆': 3, '云南': 6, '贵州': 2, '吉林': 3, '山西': 12, '山东': 11, '福建': 4, '青海': 1, '舵主科技,质量保证': 1, '天津': 1, '其他': 1}
    # provice=list(province_distribution.keys())
    # values=list(province_distribution.values())
    years = list(df.index)
    geos = []
    timeline = Timeline(width=1700,height=900,is_auto_play=True, timeline_bottom=-10,timeline_symbol_size=20,timeline_play_interval=400,timeline_left=20,timeline_right=100 , \
        is_timeline_show = False )
    for index in range(len(years)):
        cities = list(df.columns)
        cities.remove('total')
        values = list(df.loc[years[index], :])
        total_num = values[-1]
        del (values[-1])
        # print(cities)
        # print(values)

        geos.append(Geo( str(int(total_num)), title_top="10%" , title_text_size=50 , subtitle = years[index] +" , subtitle",  \
            subtitle_text_size = 23 , subtitle_color="white", \
            title_color="red", title_pos="center", width=1200, height=600, \
            background_color='#404a59'))
        # type="effectScatter", is_random=True, effect_scale=5  使点具有发散性
        geos[index].add("title level1", cities, values, type="effectScatter", maptype='china' , is_random=True, effect_scale=3,  is_selected = True,is_toolbox_show = True ,is_more_utils =True,\
            visual_text_color="#fff", symbol_size=10, is_label_show = True ,  legend_orient = 'left' ,is_legend_show = False, legend_top = 'bottom' , label_formatter = '{b}' , \
            is_visualmap=True, is_roam=True , label_text_color="#00FF00" , is_piecewise=True, label_text_size = 7,visual_range=[1, 300] , \
            geo_cities_coords = {'赣江': [115.934192 , 28.826235] , '红河州' : [103.381549,23.369996] , '蒙自' : [103.371546,23.40208] , '海安' : [120.469259,32.544553] , \
                '济阳' : [117.023094,36.965519] , '库车' : [82.970183,41.733785] , '文山-砚山' : [104.334442,23.621612] , '文安':[116.455985,38.891083] , '罗平':[104.309188,24.890519] , \
                '宣城' : [118.762662,30.957007] , '古田' : [118.747401,26.596702] , '泗阳':[118.699691,33.723524] , }  , \
            pieces=[
                {"min":0.1, "max": 50 , "label": "0-50"},
                {"min": 51, "max": 100 , "label": "51-100"},
                {"min": 101, "max": 200 , "label": "101-200"},
                {"min":201, "max": 500, "label": "201-500"},
                {"min":500, "max": 2900, "label": ">500"}, ] )
        geos[index].show_config()
        geos[index].render("xxxx售出数量.html")
        #   时间轴定义
        timeline.add(geos[index], years[index])
    timeline.render('final_graph.html')
コード例 #23
0
def test_timeline_bar():
    bar_1 = Bar("2012 年销量", "数据纯属虚构")
    bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_2 = Bar("2013 年销量", "数据纯属虚构")
    bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_3 = Bar("2014 年销量", "数据纯属虚构")
    bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_4 = Bar("2015 年销量", "数据纯属虚构")
    bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_5 = Bar("2016 年销量", "数据纯属虚构")
    bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("冬季",
              CLOTHES, [randint(10, 100) for _ in range(6)],
              is_legend_show=True)

    timeline = Timeline(is_auto_play=True, timeline_bottom=0)
    timeline.add(bar_1, '2012 年')
    timeline.add(bar_2, '2013 年')
    timeline.add(bar_3, '2014 年')
    timeline.add(bar_4, '2015 年')
    timeline.add(bar_5, '2016 年')
    timeline.render()
コード例 #24
0
ファイル: test_timeline.py プロジェクト: chumingke/pyecharts
def test_timeline_bar():
    bar_1 = Bar("2012 年销量", "数据纯属虚构")
    bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_2 = Bar("2013 年销量", "数据纯属虚构")
    bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_3 = Bar("2014 年销量", "数据纯属虚构")
    bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_4 = Bar("2015 年销量", "数据纯属虚构")
    bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_5 = Bar("2016 年销量", "数据纯属虚构")
    bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)],
              is_legend_show=True)

    timeline = Timeline(is_auto_play=True, timeline_bottom=0)
    timeline.add(bar_1, '2012 年')
    timeline.add(bar_2, '2013 年')
    timeline.add(bar_3, '2014 年')
    timeline.add(bar_4, '2015 年')
    timeline.add(bar_5, '2016 年')
    timeline.render()
コード例 #25
0
ファイル: chart13.py プロジェクト: snowind/pyecharts-sample
          rosetype='radius')

pie_3 = Pie("2014 年销量比例", "数据纯属虚构")
pie_3.add("秋季",
          attr, [random.randint(10, 100) for _ in range(6)],
          is_label_show=True,
          radius=[30, 55],
          rosetype='radius')

pie_4 = Pie("2015 年销量比例", "数据纯属虚构")
pie_4.add("秋季",
          attr, [random.randint(10, 100) for _ in range(6)],
          is_label_show=True,
          radius=[30, 55],
          rosetype='radius')

pie_5 = Pie("2016 年销量比例", "数据纯属虚构")
pie_5.add("秋季",
          attr, [random.randint(10, 100) for _ in range(6)],
          is_label_show=True,
          radius=[30, 55],
          rosetype='radius')

timeline = Timeline(is_auto_play=True, timeline_bottom=0)
timeline.add(pie_1, '2012 年')
timeline.add(pie_2, '2013 年')
timeline.add(pie_3, '2014 年')
timeline.add(pie_4, '2015 年')
timeline.add(pie_5, '2016 年')
timeline.render('./picture13.html')
コード例 #26
0
timeline = Timeline(is_auto_play=False, timeline_bottom=0)

df["time_ymd"] = df["time"].apply(lambda x: x[:10])
grouped = copy.deepcopy(df.groupby("time_ymd"))  #根据日期进行分组

for single in grouped:
    date = single[0]
    dff = pd.DataFrame()
    # dff=single[1]
    # print(dff.loc[:,"area"])
    dff.loc[:, "area"] = single[1].loc[:, "area"].apply(handleArea)
    dff.dropna(axis=0)
    arr = dff.groupby("area")["area"].count(
    )  #该时间段的每个地区的评论数,返回Series,index是每组的"area",values是评论数
    # attr=dff.groupby("area")
    # print(type(arr))
    tempGeo = Geo("%s日评论数" % date,
                  "“中国年轻人正带领国家走向危机”,这锅背是不背?",
                  title_color="#fff",
                  title_pos="center",
                  width=1200,
                  height=600,
                  background_color="#404a59")
    # print(arr.values)
    tempGeo.add("", arr.index, arr.values, is_visualmap=True)
    timeline.add(tempGeo, "%s" % date)
    # print(single[1])

timeline.render("时间线图.html")
コード例 #27
0
    def queren(self):
        date_field = self.comboBox.currentText()
        startdate = self.comboBox_3.currentText()
        enddate = self.comboBox_2.currentText()
        spacefield = self.comboBox_4.currentText()
        space_val = self.comboBox_6.currentText()
        maptype_val = self.comboBox_7.currentText()
        aoi_val = self.comboBox_8.currentText()
        db = pymysql.connect("localhost",
                             "root",
                             "960609",
                             "biye",
                             charset='utf8')
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        #找对应的时间
        if space_val == 'china' or space_val == 'world':
            datetime_sql='select distinct '+ date_field+' from AOI where '+date_field+\
                     ' between \''+startdate+'\' and \''+enddate+'\''
        else:
            #这里字段写死了,表中一定要有province字段
            datetime_sql='select distinct '+ date_field+' from AOI where province'+'=\''+space_val+'\' and '+date_field+\
                     ' between \''+startdate+'\' and \''+enddate+'\''
        cursor.execute(datetime_sql)
        rows = cursor.fetchall()
        time_val = []
        for (row, ) in rows:
            timeval = str(row)
            time_val.append(timeval)

        # 加入时间轴
        timeline = Timeline()
        #单张地图
        for i in range(len(time_val)):
            # 查找地名
            if space_val == 'china' or space_val == 'world':
                location_sql = 'select ' + spacefield + ' from AOI where ' + date_field + '=\'' + time_val[
                    i] + '\''
            else:
                location_sql = 'select ' + spacefield + ' from AOI where province =\'' + space_val + '\' and ' + date_field + \
                               '=\'' + time_val[i]+'\''
            cursor.execute(location_sql)
            rows = cursor.fetchall()
            location_val = []
            for (row, ) in rows:
                locationval = str(row)
                location_val.append(locationval)

            # 查找值
            if space_val == 'china' or space_val == 'world':
                value_sql = 'select ' + aoi_val + ' from AOI where ' + date_field + '=\'' + time_val[
                    i] + '\''
            else:
                value_sql = 'select ' + aoi_val + ' from AOI where province'+ '=\'' + space_val + '\' and ' + date_field + \
                            '=\'' + time_val[i]+'\''
            cursor.execute(value_sql)
            rows = cursor.fetchall()
            val = []
            for (row, ) in rows:
                aoival = str(row)
                val.append(aoival)

            # 设置一张地图
            geo = Geo("", width=1000, height=600, background_color='#404a59')
            self.drawtimeline(location_val, val, geo, space_val, maptype_val)
            timeline.add(geo, str(time_val[i]))
        timeline.render("test.html")
        self.dywebmap.show_table()
コード例 #28
0
def stock_render_page(stock_info, start_date, end_date, interval, width,
                      height):
    page = Page()
    stock_name = stock_info.split('-', 2)[0]
    stock_id = stock_info.split('-', 2)[1]
    action = stock_info.split('-', 2)[2]
    a = generate_stock_line(
        stock_id, action, start_date, end_date,
        interval)  # stock number, Type, startdate, enddate, 30 or 15 or days
    if a is None:
        return
    if action == "Kline":
        time, open, close, low, high = zip(
            *a)  # get time from returned dictionary
    else:
        time, target = zip(*a)
        a = [time, target]
    if action != "Kline":
        if len(time[0]) == 4 and time[0][2] == "bar":  # for 分笔data
            overlap = Overlap()
            form = [e[1] for e in a]
            bar = Bar(stock_name + "-" + stock_id + "-" + action,
                      width=width * 10 / 11,
                      height=(height * 10 / 11))
            bar.add(stock_name + "-" + stock_id + "-" + action,
                    time,
                    form,
                    yaxis_min="dataMin",
                    yaxis_max="dataMax",
                    is_datazoom_show=True,
                    datazoom_type="slider")
            overlap.add(bar)

            line = Line(stock_name + "price" + "-" + action,
                        width=width * 10 / 11,
                        height=(height * 10 / 11))
            price = [e[3] for e in a]
            line.add(stock_name + "price" + "-" + action,
                     time,
                     price,
                     yaxis_min="dataMin",
                     yaxis_max="dataMax",
                     is_datazoom_show=True,
                     datazoom_type="slider",
                     yaxis_type="value")
            overlap.add(line, yaxis_index=1, is_add_yaxis=True)
            page.add(overlap)
        if len(a[0]) == 5 and a[0][3] == "pie":
            overlap = Overlap()
            time_line = Timeline(
                is_auto_play=False, timeline_bottom=0
            )  # zip(namearray,valuearray,quarter,flag,num)
            name_array = [c[0] for c in a]
            value_array = [d[1] for d in a]
            quarter = [e[2] for e in a]
            num = a[0][4]
            for x in range(0, num / 10):
                list1 = value_array[x]
                names = name_array[x]
                quarters = quarter[x][0]
                for idx, val in enumerate(list1):
                    list1[idx] = float(val)
                pie = Pie("前十股东",
                          width=width * 10 / 11,
                          height=(height * 10 / 11))
                pie.add("前十股东",
                        names,
                        list1,
                        radius=[30, 55],
                        is_legend_show=False,
                        is_label_show=True,
                        label_formatter="{b}: {c}\n{d}%")
                # print list
                # print names
                # print quarterarray

                time_line.add(pie, quarters)
                # namearray = [y for y in namearray[x]]
            time_line.render()
            return

            # need more statement
        else:
            line = Line(stock_name + "-" + stock_id + "-" + action,
                        width=width * 10 / 11,
                        height=(height * 10 / 11))
            line.add(stock_name + "-" + stock_id + "-" + action,
                     time,
                     target,
                     is_datazoom_show=True,
                     datazoom_type="slider",
                     yaxis_min="dataMin",
                     yaxis_max="dataMax")
            page.add(line)
            page.add(line)
    else:
        overlap = Overlap()  #for k线
        candle = [open, close, low, high]
        candlestick = Kline(stock_name + "-" + stock_id + "-" + action,
                            width=width * 10 / 11,
                            height=(height * 10 / 11))
        candlestick.add(stock_name + "-" + stock_id + "-" + action,
                        time,
                        candle,
                        is_datazoom_show=True,
                        datazoom_type="slider",
                        yaxis_interval=1)
        overlap.add(candlestick)
        if len(close) > 10:
            ma10 = calculate_month(close, 10)
            line1 = Line(title_color="#C0C0C0")
            line1.add(stock_name + "-" + "MA10" + "-" + action, time, ma10)
            overlap.add(line1)
        if len(close) > 20:
            ma20 = calculate_month(close, 20)
            line2 = Line(title_color="#C0C0C0")
            line2.add(stock_name + "-" + "MA20" + "-" + action, time, ma20)
            overlap.add(line2)
        if len(close) > 30:
            ma30 = calculate_month(close, 30)
            line3 = Line(title_color="#C0C0C0")
            line3.add(stock_name + "-" + "MA30" + "-" + action, time, ma30)
            overlap.add(line3)
        page.add(overlap)
    page.render()
コード例 #29
0
	def draw_month_timeline(df,time_col,tgt,time_type=None,time_format='%Y-%m-%d %H:%M:%S',file_name='month_timeline.html',draw_type='timeline'):
		month_30=[4,6,9,11]
		month_31=[1,3,5,7,8,10,12]
		if time_type == 'timestamp':
			temp_time = df[time_col].map(lambda x: datetime.datetime.date(datetime.datetime.fromtimestamp(int(x))))
		elif time_type == 'str':
			temp_time = df[time_col].map(lambda x: datetime.datetime.date(datetime.datetime.strptime(x,time_format)))
		else:
			temp_time = df[time_col].map(lambda x: datetime.datetime.date(x))
		temp = pd.concat([temp_time,df[tgt]],axis=1)
		temp['day'] = temp[time_col].map(lambda x: x.day)
		min_time = temp[time_col].min()
		max_time = temp[time_col].max()
		month_interval = (max_time.year-min_time.year)*12+(max_time.month-min_time.month)+1
		color_list = draw.random_color_list(month_interval)
		start_time = datetime.datetime.date(datetime.datetime.\
											strptime(str(temp[time_col].min().year)+'-'+str(temp[time_col].min().month)+'-01',"%Y-%m-%d"))
		if draw_type == 'timeline':
			timeline = Timeline(timeline_bottom=0)
			while start_time<max_time:
				if (start_time.month in month_30):
					month_day = 30
				elif (start_time.month in month_31):
					month_day = 31
				elif (start_time.month==2&(((start_time.year%100 == 0)&((start_time.year/100%4)==0))|((start_time.year%100!=0)&((start_time.year%4)==0)))):
					month_day = 29
				else:
					month_day = 28
				temp_df = temp[((temp[time_col]>=start_time)&(temp[time_col]<start_time+relativedelta(months=1)))]
				temp_df_size = temp_df.groupby(['day']).size()
				temp_df_mean = temp_df.groupby(['day']).mean()
				time_df = pd.concat([temp_df_size,temp_df_mean],axis=1)
				time_df.rename(columns={0:'size'},inplace=True)
				idx = time_df.index.values[(np.abs(time_df[tgt].values-time_df[tgt].mean())).argmin()]
				mean_val = time_df[tgt].loc[idx]
				missing_day = list(set(range(1,month_day+1))-set(time_df.index.values))
				if len(missing_day)>0:
					missing_len = len(missing_day)
					missing_size = list(np.zeros(missing_len))
					missing_mean = list(np.zeros(missing_len))
					temp_missing_df = pd.DataFrame([missing_day,missing_size,missing_mean]).T
					temp_missing_df.rename(columns={0:'day',1:'size',2:tgt},inplace=True)
					temp_missing_df.set_index('day',inplace=True)
					time_df = pd.concat([time_df,temp_missing_df])
				time_df.sort_index(inplace=True)
				time_df.index = time_df.index.values.astype(int)
				x_axis_label = ['{}'.format(i) for i in time_df.index.values.tolist()]
				bar = Bar("{}年{}月份数据".format(start_time.year,start_time.month))
				bar.add("数量", x_axis_label, time_df['size'].values.tolist(),label_color=color_list,\
						label_emphasis_textcolor='#000000',is_more_utils=True)
				line = Line()
				line.add("{} rate".format(tgt), x_axis_label, round(time_df[tgt],2).values.tolist(),label_color=color_list,\
						 mark_point=[{"coord":[str(idx),round(mean_val,2)],"name":"mean value"}],\
						 label_emphasis_textcolor='#000000')
				overlap = Overlap()
				overlap.add(bar)
				overlap.add(line, yaxis_index=1, is_add_yaxis=True)
				timeline.add(overlap,"{}-{}".format(start_time.year,start_time.month))
				start_time += relativedelta(months=1)
			print('File rendered at {}'.format(os.path.join(ROOT_DIR,file_name)))
			return timeline.render(os.path.join(ROOT_DIR,file_name))
		elif draw_type == 'all_in_one':
			month_day = 31
			overlap = Overlap()
			while start_time<max_time:
				temp_df = temp[((temp[time_col]>=start_time)&(temp[time_col]<start_time+relativedelta(months=1)))]
				time_df = temp_df.groupby(['day']).mean()
				idx = time_df.index.values[(np.abs(time_df[tgt].values-time_df[tgt].mean())).argmin()]
				mean_val = time_df[tgt].loc[idx]
				missing_day = list(set(range(1,month_day+1))-set(time_df.index.values))
				time_df.sort_index(inplace=True)
				time_df.index = time_df.index.values.astype(int)
				x_axis_label = ['{}'.format(i) for i in time_df.index.values.tolist()]
				line = Line("{} rate数据".format(tgt))
				line.add("{}-{}".format(start_time.year,start_time.month), \
						 x_axis_label, round(time_df[tgt],2).values.tolist(),label_color=color_list,\
						 mark_point=[{"coord":[str(idx),round(mean_val,2)],"name":"mean value"}],\
						 label_emphasis_textcolor='#000000',is_more_utils=True)
				overlap.add(line)
				start_time += relativedelta(months=1)
			return overlap
コード例 #30
0
ファイル: Graph.py プロジェクト: lightlogic5/TuChart
def graphpage(items,startdate,enddate,option,width1, height1): #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
    page = Page()
    for i in items:#generate numbers of graphs according to numbers of queries in treewidget
        j = re.split("-",i)
        if len(j)==3:
            a = generateline(j[1],j[2],startdate,enddate,option)#stock number, Type, startdate, enddate, 30 or 15 or days
            if a is None:
                continue
            time = [d[0] for d in a]#get time from returned dictionary
            if j[2]!="Kline":

                if len(a[0])==4 and a[0][2]=="bar": #for 分笔data
                    overlap = Overlap()
                    form = [e[1] for e in a]
                    bar = Bar(j[0] + "-" + j[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                    bar.add(j[0] + "-" + j[2], time, form, yaxis_min = "dataMin",yaxis_max = "dataMax",is_datazoom_show = True, datazoom_type = "slider")
                    overlap.add(bar)

                    line = Line(j[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                    price = [e[3] for e in a]
                    line.add(j[0] + "price", time, price, yaxis_min = "dataMin",yaxis_max = "dataMax", is_datazoom_show = True, datazoom_type = "slider",
                            yaxis_type="value")
                    overlap.add(line,yaxis_index=1, is_add_yaxis=True)

                    page.add(overlap)

                if len(a[0])==5 and a[0][3]=="pie":
                    overlap = Overlap()
                    timeline = Timeline(is_auto_play=False, timeline_bottom=0) #zip(namearray,valuearray,quarter,flag,num)
                    namearray = [c[0] for c in a]
                    valuearray = [d[1] for d in a]
                    quarter = [e[2] for e in a]
                    num = a[0][4]

                    for x in range(0, num / 10):
                        list1 = valuearray[x]
                        names = namearray[x]
                        quarters = quarter[x][0]

                        for idx, val in enumerate(list1):
                            list1[idx] = float(val)

                        pie = Pie(j[0]+"-"+"前十股东".decode("utf-8"),width=width1 * 10 / 11, height=(height1 * 10 / 11))

                        pie.add(j[0]+"-"+"前十股东".decode("utf-8"), names, list1, radius=[30, 55], is_legend_show=False,
                                is_label_show=True, label_formatter = "{b}: {c}\n{d}%")
                        # print list
                        # print names
                        # print quarterarray

                        timeline.add(pie, quarters)
                        # namearray = [y for y in namearray[x]]
                    timeline.render()

                    return


                    #need more statement
                else:
                    form = [e[1] for e in a]#for not分笔 data
                    line = Line(j[0] + "-" + j[2], width=width1*10/11, height=(height1*10/11)/len(items))
                    line.add(j[0] + "-" + j[2], time, form, is_datazoom_show=True, datazoom_type="slider",yaxis_min="dataMin",yaxis_max="dataMax")
                    page.add(line)
            else:
                overlap = Overlap()#for k线
                close = zip(*a)[2]
                candle = [[x[1], x[2], x[3], x[4]] for x in a]
                candlestick = Kline(j[0] + "-" + j[2], width=width1*10/11, height = (height1*10/11) / len(items))
                candlestick.add(j[0], time, candle, is_datazoom_show=True, datazoom_type="slider",yaxis_interval = 1)
                overlap.add(candlestick)
                if len(close)>10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(j[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close)>20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(j[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close)>30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(j[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)
                page.add(overlap)
        else:
            for k in range(1, len(j)/3):#if graphs are combined
                j[3*k-1] = re.sub("\n&","",j[3*k-1])
            sizearray=[]
            #if j[1] != "Candlestick"
            layout = Overlap()
            for i in xrange(0, len(j),3):
                array = j[i:i +3]
                b = generateline(array[1],array[2],startdate,enddate,option)
                if b is None:
                    continue
                btime = [d[0] for d in b]
                if array[2] != "Kline":

                    if len(b[0])==4 and b[0][2]=="bar":
                        form = [e[1] for e in b]
                        bar = Bar(array[0] + "-" + array[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                        bar.add(array[0] + "-" + array[2], btime, form, is_datazoom_show=True, datazoom_type="slider",
                                yaxis_min="dataMin", yaxis_max="dataMax")
                        layout.add(bar)
                        line = Line(array[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                        price = [e[3] for e in b]
                        line.add(array[0] + "price", btime, price, is_datazoom_show=True, datazoom_type="slider",
                                     yaxis_min="dataMin", yaxis_type="value")
                        layout.add(line, yaxis_index=1, is_add_yaxis=True)




                    else:
                        line = Line(array[0] + "-" + array[2],width=width1*10/11, height=(height1*10/11) / len(items))
                        line.add(array[0]+"-"+array[2], btime, b, is_datazoom_show=True, yaxis_max = "dataMax", yaxis_min = "dataMin",datazoom_type="slider")
                        layout.add(line)
                else:
                    candle = [[x[1], x[2], x[3], x[4]] for x in b]
                    candlestick = Kline(array[0] + "-" + array[1], width=width1*10/11,
                                        height=(height1*10/11) / len(items))
                    candlestick.add(array[0], btime, candle, is_datazoom_show=True, datazoom_type=["slider"])

                    #if i == 0:
                    close = zip(*b)[2]
                    if len(close)>10:
                        ma10 = calculateMa(close, 10)
                        line4 = Line(title_color="#C0C0C0")
                        line4.add(array[0] + "-" + "MA10", btime, ma10)
                        layout.add(line4)
                    if len(close)>20:
                        ma20 = calculateMa(close, 20)
                        line5 = Line(title_color="#C0C0C0")
                        line5.add(array[0] + "-" + "MA20", btime, ma20)
                        layout.add(line5)
                    if len(close)>30:
                        ma30 = calculateMa(close, 30)
                        line6 = Line(title_color="#C0C0C0")
                        line6.add(array[0] + "-" + "MA30", btime, ma30)
                        layout.add(line6)
                    layout.add(candlestick)
            page.add(layout)
    page.render()
コード例 #31
0
    rosetype="radius",
)

pie_4 = Pie("2015 年销量比例", "数据纯属虚构")
pie_4.add(
    "秋季",
    attr,
    [randint(10, 100) for _ in range(6)],
    is_label_show=True,
    radius=[30, 55],
    rosetype="radius",
)

pie_5 = Pie("2016 年销量比例", "数据纯属虚构")
pie_5.add(
    "秋季",
    attr,
    [randint(10, 100) for _ in range(6)],
    is_label_show=True,
    radius=[30, 55],
    rosetype="radius",
)

timeline = Timeline(is_auto_play=True, timeline_bottom=0)
timeline.add(pie_1, '2012 年')
timeline.add(pie_2, '2013 年')
timeline.add(pie_3, '2014 年')
timeline.add(pie_4, '2015 年')
timeline.add(pie_5, '2016 年')
timeline.render()
コード例 #32
0
ファイル: Graph.py プロジェクト: lightlogic5/TuChart
def graphpage(labels,mode_combo,startdate,enddate,optInterval,width1, height1):
    #optInterval='D/W/M' labels

    startdate = startdate.replace("/","-")#convert to tushare readable date
    enddate = enddate.replace("/","-")

    page = Page()

    for label in labels:  # generate numbers of graphs according to numbers of queries in treewidget
        label1 = re.split("-", label)
        overlap = Overlap()

        if label1[2]!="分笔" and label1[2]!="季度饼图": #"K线" "复权" "历史分钟"
            if mode_combo == "复权":
            #if optInterval == "qfq" or optInterval == "hfq":#复权
                array = ts.get_h_data(label1[1], start=startdate, end=enddate, autype="qfq")
                array = array.sort_index()
                time = array.index.format()  # 日期正是index
            elif mode_combo == "K线":
            #elif optInterval.isalnum() :#历史K线
                array = ts.get_k_data(label1[1], start=startdate, end=enddate, ktype=optInterval)
                time = array['date'].tolist()  # array.date
            elif mode_combo == "历史分钟":
                array_bfr = ts.get_tick_data(label1[1], date=startdate)
                array_bfr.sort_values("time")
                a = startdate + " " + array_bfr["time"]
                array_bfr["time"] = a
                array_bfr["time"] = pd.to_datetime(a)
                array_bfr = array_bfr.set_index("time")
                if label1[2] != "Volume" and label1[2] != "Amount":
                    price_df = array_bfr["price"].resample(optInterval).ohlc()  # resample重新取样,选出ohlc=open/high/low,提取除价格之外另外4列.close,tushare是ohcl
                    price_df = price_df.dropna()
                    array = price_df
                    time = price_df.index.format()

                elif label1[2] == "Volume":
                    vols = array_bfr["volume"].resample(optInterval).sum()  #resample重新取样,累加间隔内数值 relevant data processing algorithm taken from Jimmy, Creator of Tushare
                    vols = vols.dropna()
                    vol_df = pd.DataFrame(vols, columns=["volume"])
                    array = vol_df
                    time = vol_df.index.format()
                else:
                    amounts = array_bfr["amount"].resample(optInterval).sum()
                    amounts = amounts.dropna()
                    amount_df = pd.DataFrame(amounts, columns=["amount"])
                    array = amount_df
                    time = amount_df.index.format()

            #绘图方法

            if label1[2] == 'Kline':
                re_array = array[['open', 'close', 'high', 'low']]
                data_li = list(row.tolist() for index, row in re_array.iterrows())  # data_list = list(re_array.as_matrix())
                close = array['close'].tolist()
                kline = Kline(label1[0] + "-" + optInterval, width=width1*10/11, height = (height1*10/11) / len(labels))
                kline.add(label1[0], time, data_li, is_datazoom_show=True, datazoom_type="slider", yaxis_interval=1)
                overlap.add(kline)

                if len(close) > 10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(label1[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close) > 20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(label1[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close) > 30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(label1[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)

                page.add(overlap)
            else:#When label1[2]==open/close/volume
                if label1[2] == 'Open':
                    list_aft = array['open'].tolist()
                elif label1[2] == 'Close':
                    list_aft = close
                elif label1[2] == 'High':
                    list_aft = array['high'].tolist()
                elif label1[2] == 'Low':
                    list_aft = array['low'].tolist()
                elif label1[2] == 'Volume':#volume
                    list_aft = array['volume'].tolist()
                else:#amount
                    list_aft = array['amount'].tolist()

                line = Line(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
                line.add(label1[0] + "-" + label1[2], time, list_aft, is_datazoom_show=True, yaxis_max="dataMax",
                         yaxis_min="dataMin", datazoom_type="slider")
                overlap.add(line)
                page.add(overlap)


        elif label1[2]=="分笔":
            array = ts.get_tick_data(label1[1], date=startdate)
            array = array.sort_values("time")
            date = array["time"].tolist()
            amount = array["amount"].tolist()
            atype = array["type"].tolist()
            price = array["price"].tolist()
            flag = ["bar" for i in date]
            for idx, val in enumerate(atype):
                if val == "卖盘":
                    amount[idx] = -amount[idx]
                if val == "中性盘":
                    amount[idx] = 0

            returnarray = list(zip(date, amount, flag, price))

            form = [e[1] for e in returnarray]
            time = [d[0] for d in returnarray]

            bar = Bar(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
            bar.add(label1[0] + "-" + label1[2], time, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax")
            overlap.add(bar)

            line = Line(label1[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
            price = [e[3] for e in returnarray]
            line.add(label1[0] + "price", time, price, yaxis_min="dataMin", yaxis_max="dataMax", is_datazoom_show=True,
                     datazoom_type="slider",
                     yaxis_type="value")
            overlap.add(line, yaxis_index=1, is_add_yaxis=True)
            page.add(overlap)
        elif label1[2]=="季度饼图":
            datestr = startdate.split("-")
            thisyear = datestr[0]
            df2 = ts.top10_holders(code=label1[1], gdtype="1")
            test = df2[1]["quarter"].tolist()
            df_ready = df2[1]
            idxlist = []
            for idx, val in enumerate(test):
                a = val.split("-")
                if a[0] == thisyear:
                    # print a[0],idx
                    idxlist.append(idx)
            thing = df_ready.loc[idxlist]
            thing = thing.sort_values(["quarter", "name"])
            # print a[0],id
            name = thing["name"].tolist()
            value = thing["hold"].tolist()
            quarter = thing["quarter"].tolist()
            namearray = [name[i:i + 10] for i in range(0, len(name), 10)]
            valuearray = [value[j:j + 10] for j in range(0, len(value), 10)]
            quarterarray = [quarter[k:k + 10] for k in range(0, len(quarter), 10)]

            flag = ["pie" for i in namearray]
            num = [len(value) for k in namearray]
            returnarray = list(zip(namearray, valuearray, quarterarray, flag, num))

            timeline = Timeline(is_auto_play=False, timeline_bottom=0)  # zip(namearray,valuearray,quarter,flag,num)
            namearray = [c[0] for c in returnarray]
            valuearray = [d[1] for d in returnarray]
            quarter = [e[2] for e in returnarray]
            num = returnarray[0][4]

            for x in range(0, int(num / 10)):
                list1 = valuearray[x]
                names = namearray[x]
                quarters = quarter[x][0]

                for idx, val in enumerate(list1):
                    list1[idx] = float(val)

                pie = Pie(label1[0] + "-" + "前十股东", width=width1 * 10 / 11, height=(height1 * 10 / 11))

                pie.add(label1[0] + "-" + "前十股东", names, list1, radius=[30, 55], is_legend_show=False,
                        is_label_show=True, label_formatter="{b}: {c}\n{d}%")
                timeline.add(pie, quarters)
                # namearray = [y for y in namearray[x]]
            timeline.render()

    page.render()
コード例 #33
0
ファイル: Graph.py プロジェクト: ynzhang99/quant
def graphpage(items, startdate, enddate, option, width1,
              height1):  #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
    page = Page()
    for i in items:  #generate numbers of graphs according to numbers of queries in treewidget
        j = re.split("-", i)
        if len(j) == 3:
            a = generateline(
                j[1], j[2], startdate, enddate, option
            )  #stock number, Type, startdate, enddate, 30 or 15 or days
            if a is None:
                continue
            time = [d[0] for d in a]  #get time from returned dictionary
            if j[2] != "Kline":

                if len(a[0]) == 4 and a[0][2] == "bar":  #for 分笔data
                    overlap = Overlap()
                    form = [e[1] for e in a]
                    bar = Bar(j[0] + "-" + j[2],
                              width=width1 * 10 / 11,
                              height=(height1 * 10 / 11) / len(items))
                    bar.add(j[0] + "-" + j[2],
                            time,
                            form,
                            yaxis_min="dataMin",
                            yaxis_max="dataMax",
                            is_datazoom_show=True,
                            datazoom_type="slider")
                    overlap.add(bar)

                    line = Line(j[0] + "price",
                                width=width1 * 10 / 11,
                                height=(height1 * 10 / 11) / len(items))
                    price = [e[3] for e in a]
                    line.add(j[0] + "price",
                             time,
                             price,
                             yaxis_min="dataMin",
                             yaxis_max="dataMax",
                             is_datazoom_show=True,
                             datazoom_type="slider",
                             yaxis_type="value")
                    overlap.add(line, yaxis_index=1, is_add_yaxis=True)

                    page.add(overlap)

                if len(a[0]) == 5 and a[0][3] == "pie":
                    overlap = Overlap()
                    timeline = Timeline(
                        is_auto_play=False, timeline_bottom=0
                    )  #zip(namearray,valuearray,quarter,flag,num)
                    namearray = [c[0] for c in a]
                    valuearray = [d[1] for d in a]
                    quarter = [e[2] for e in a]
                    num = a[0][4]

                    for x in range(0, num / 10):
                        list1 = valuearray[x]
                        names = namearray[x]
                        quarters = quarter[x][0]

                        for idx, val in enumerate(list1):
                            list1[idx] = float(val)

                        pie = Pie(j[0] + "-" + "前十股东".decode("utf-8"),
                                  width=width1 * 10 / 11,
                                  height=(height1 * 10 / 11))

                        pie.add(j[0] + "-" + "前十股东".decode("utf-8"),
                                names,
                                list1,
                                radius=[30, 55],
                                is_legend_show=False,
                                is_label_show=True,
                                label_formatter="{b}: {c}\n{d}%")
                        # print list
                        # print names
                        # print quarterarray

                        timeline.add(pie, quarters)
                        # namearray = [y for y in namearray[x]]
                    timeline.render()

                    return

                    #need more statement
                else:
                    form = [e[1] for e in a]  #for not分笔 data
                    line = Line(j[0] + "-" + j[2],
                                width=width1 * 10 / 11,
                                height=(height1 * 10 / 11) / len(items))
                    line.add(j[0] + "-" + j[2],
                             time,
                             form,
                             is_datazoom_show=True,
                             datazoom_type="slider",
                             yaxis_min="dataMin",
                             yaxis_max="dataMax")
                    page.add(line)
            else:
                overlap = Overlap()  #for k线
                close = zip(*a)[2]
                candle = [[x[1], x[2], x[3], x[4]] for x in a]
                candlestick = Kline(j[0] + "-" + j[2],
                                    width=width1 * 10 / 11,
                                    height=(height1 * 10 / 11) / len(items))
                candlestick.add(j[0],
                                time,
                                candle,
                                is_datazoom_show=True,
                                datazoom_type="slider",
                                yaxis_interval=1)
                overlap.add(candlestick)
                if len(close) > 10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(j[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close) > 20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(j[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close) > 30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(j[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)
                page.add(overlap)
        else:
            for k in range(1, len(j) / 3):  #if graphs are combined
                j[3 * k - 1] = re.sub("\n&", "", j[3 * k - 1])
            sizearray = []
            #if j[1] != "Candlestick"
            layout = Overlap()
            for i in xrange(0, len(j), 3):
                array = j[i:i + 3]
                b = generateline(array[1], array[2], startdate, enddate,
                                 option)
                if b is None:
                    continue
                btime = [d[0] for d in b]
                if array[2] != "Kline":

                    if len(b[0]) == 4 and b[0][2] == "bar":
                        form = [e[1] for e in b]
                        bar = Bar(array[0] + "-" + array[2],
                                  width=width1 * 10 / 11,
                                  height=(height1 * 10 / 11) / len(items))
                        bar.add(array[0] + "-" + array[2],
                                btime,
                                form,
                                is_datazoom_show=True,
                                datazoom_type="slider",
                                yaxis_min="dataMin",
                                yaxis_max="dataMax")
                        layout.add(bar)
                        line = Line(array[0] + "price",
                                    width=width1 * 10 / 11,
                                    height=(height1 * 10 / 11) / len(items))
                        price = [e[3] for e in b]
                        line.add(array[0] + "price",
                                 btime,
                                 price,
                                 is_datazoom_show=True,
                                 datazoom_type="slider",
                                 yaxis_min="dataMin",
                                 yaxis_type="value")
                        layout.add(line, yaxis_index=1, is_add_yaxis=True)

                    else:
                        line = Line(array[0] + "-" + array[2],
                                    width=width1 * 10 / 11,
                                    height=(height1 * 10 / 11) / len(items))
                        line.add(array[0] + "-" + array[2],
                                 btime,
                                 b,
                                 is_datazoom_show=True,
                                 yaxis_max="dataMax",
                                 yaxis_min="dataMin",
                                 datazoom_type="slider")
                        layout.add(line)
                else:
                    candle = [[x[1], x[2], x[3], x[4]] for x in b]
                    candlestick = Kline(array[0] + "-" + array[1],
                                        width=width1 * 10 / 11,
                                        height=(height1 * 10 / 11) /
                                        len(items))
                    candlestick.add(array[0],
                                    btime,
                                    candle,
                                    is_datazoom_show=True,
                                    datazoom_type=["slider"])

                    #if i == 0:
                    close = zip(*b)[2]
                    if len(close) > 10:
                        ma10 = calculateMa(close, 10)
                        line4 = Line(title_color="#C0C0C0")
                        line4.add(array[0] + "-" + "MA10", btime, ma10)
                        layout.add(line4)
                    if len(close) > 20:
                        ma20 = calculateMa(close, 20)
                        line5 = Line(title_color="#C0C0C0")
                        line5.add(array[0] + "-" + "MA20", btime, ma20)
                        layout.add(line5)
                    if len(close) > 30:
                        ma30 = calculateMa(close, 30)
                        line6 = Line(title_color="#C0C0C0")
                        line6.add(array[0] + "-" + "MA30", btime, ma30)
                        layout.add(line6)
                    layout.add(candlestick)
            page.add(layout)
    page.render()
コード例 #34
0
                    height=700)

for hour in range(24):
    for minuteOfHour in range(12):
        mask = (pred_df['时'] == hour) & (pred_df['第x个五分钟'] == minuteOfHour)
        temp_df = temp_df.sort_values('站点')
        temp_df = pred_df[mask]
        attrs = temp_df['站点']
        values = temp_df['客流量']

        bar = Bar("24小时上海地铁客流量", "以每5分钟为统计单位", width=1400, height=600)
        bar.add("", attrs, values)
        timeline.add(
            bar, '{}时 :{}~{}分钟'.format(hour, 5 * minuteOfHour,
                                       5 * minuteOfHour + 5))
timeline.render('LSTM_24小时上海地铁客流量.html')

## 对预测结果用pyplot可视化
DFs = []  # 读取预测数据
for fileName in os.listdir('./LSTM_output/'):
    temp_df = pd.read_csv('./LSTM_output/' + fileName, encoding='gbk')
    station = fileName.split('.')[0]
    temp_df['站点'] = station
    DFs.append(temp_df)
pred_df = pd.concat(DFs)  # 把所有预测数据合并到一个数据表中
del DFs


def drop_num(station):
    '''
    把完整到站点名称删去"x号线"
コード例 #35
0
bar_3.add("冬季", attr, [random.randint(10, 100) for _ in range(6)])

bar_4 = Bar("2015年销量", "数据纯属虚构")
bar_4.add("春季", attr, [random.randint(10, 100) for _ in range(6)])
bar_4.add("夏季", attr, [random.randint(10, 100) for _ in range(6)])
bar_4.add("秋季", attr, [random.randint(10, 100) for _ in range(6)])
bar_4.add("冬季", attr, [random.randint(10, 100) for _ in range(6)])

bar_5 = Bar("2016年销量", "数据纯属虚构")
bar_5.add("春季", attr, [random.randint(10, 100) for _ in range(6)])
bar_5.add("夏季", attr, [random.randint(10, 100) for _ in range(6)])
bar_5.add("秋季", attr, [random.randint(10, 100) for _ in range(6)])
bar_5.add("冬季", attr, [random.randint(10, 100) for _ in range(6)])

bar_6 = Bar("2017年销量", "数据纯属虚构")
bar_6.add("春季", attr, [random.randint(10, 100) for _ in range(6)])
bar_6.add("夏季", attr, [random.randint(10, 100) for _ in range(6)])
bar_6.add("秋季", attr, [random.randint(10, 100) for _ in range(6)])
bar_6.add("冬季",
          attr, [random.randint(10, 100) for _ in range(6)],
          is_legend_show=True)

timeline = Timeline(is_auto_play=True, timeline_bottom=0)
timeline.add(bar_1, "2012年")
timeline.add(bar_2, "2013年")
timeline.add(bar_3, "2014年")
timeline.add(bar_4, "2015年")
timeline.add(bar_5, "2016年")
timeline.add(bar_6, "2017年")
timeline.render(path="Timeline.html")
コード例 #36
0
                    height=700)

for hour in range(24):
    for minuteOfHour in range(12):
        mask = (pred_df['时'] == hour) & (pred_df['第x个五分钟'] == minuteOfHour)
        temp_df = temp_df.sort_values('站点')
        temp_df = pred_df[mask]
        attrs = temp_df['站点']
        values = temp_df['客流量']

        bar = Bar("24小时上海地铁客流量", "以每5分钟为统计单位", width=1400, height=600)
        bar.add("", attrs, values)
        timeline.add(
            bar, '{}时 :{}~{}分钟'.format(hour, 5 * minuteOfHour,
                                       5 * minuteOfHour + 5))
timeline.render('KNN_24小时上海地铁客流量.html')

## 对预测结果用pyplot可视化
DFs = []  # 读取预测数据
for fileName in os.listdir('./knn_output/'):
    temp_df = pd.read_csv('./knn_output/' + fileName, encoding='gbk')
    station = fileName.split('.')[0]
    temp_df['站点'] = station
    DFs.append(temp_df)
pred_df = pd.concat(DFs)  # 把所有预测数据合并到一个数据表中
del DFs


def drop_num(station):
    '''
    把完整到站点名称删去"x号线"
コード例 #37
0
        pie_time.render(r'Amout_in_Each_Timezone_Pie.html')

    if not os.path.exists(r'Amount_of_Country_in_Timezone_Pie.html'):
        # 时区内小时区的数量统计
        df_gp = group(starbucks_df_time, ['Time', 'Timezone'])
        df_gp.columns = ['count']
        df_index = group(starbucks_df_time, ['Time'])
        df_index = df_index.reset_index(drop=False)
        timeline = Timeline(is_auto_play=False, timeline_bottom=0)
        for i in range(df_index.shape[0]):
            string = df_index['Time'][i]
            df_a_time = df_gp['count'][string].to_frame()
            df_a_time = df_a_time.reset_index(drop=False)
            pie = pie_pic(df_a_time, 'Amount of Starbucks in ' + string, 'Timezone', 'count')
            timeline.add(pie, 'Amount of Starbucks in ' + string)
        timeline.render(r'Amount_of_Country_in_Timezone_Pie.html')

    if not os.path.exists(r'map_time.html'):
        df_time = group(starbucks_df_time, 'Time')
        df_time_index = count_by_group(df_time, True)

        # 按时区的所有星巴克分布地图
        starbucks_category_color_time = []
        timezone_amount = []
        for index in range(starbucks_df_time.shape[0]):
            i = df_time_index['count'][df_time_index.Time == starbucks_df_time['Time'][index]]
            timezone_amount.append(i)
        starbucks_df_time.insert(0, 'timezone_amount', timezone_amount)
        draw_timezone_map(starbucks_df_time, r'map_time.html')

    if not os.path.exists(r'distribution_map_country.html'):
コード例 #38
0
ファイル: Graph.py プロジェクト: zhangxinsheng/TuChart
def graphpage(labels, mode_combo, startdate, enddate, optInterval, width1,
              height1):
    #optInterval='D/W/M' labels

    startdate = startdate.replace("/", "-")  #convert to tushare readable date
    enddate = enddate.replace("/", "-")

    page = Page()

    for label in labels:  # generate numbers of graphs according to numbers of queries in treewidget
        label1 = re.split("-", label)
        overlap = Overlap()

        if label1[2] != "分笔" and label1[2] != "季度饼图":  #"K线" "复权" "历史分钟"
            if mode_combo == "复权":
                #if optInterval == "qfq" or optInterval == "hfq":#复权
                array = ts.get_h_data(label1[1],
                                      start=startdate,
                                      end=enddate,
                                      autype="qfq")
                array = array.sort_index()
                time = array.index.format()  # 日期正是index
            elif mode_combo == "K线":
                #elif optInterval.isalnum() :#历史K线
                array = ts.get_k_data(label1[1],
                                      start=startdate,
                                      end=enddate,
                                      ktype=optInterval)
                time = array['date'].tolist()  # array.date
            elif mode_combo == "历史分钟":
                array_bfr = ts.get_tick_data(label1[1], date=startdate)
                array_bfr.sort_values("time")
                a = startdate + " " + array_bfr["time"]
                array_bfr["time"] = a
                array_bfr["time"] = pd.to_datetime(a)
                array_bfr = array_bfr.set_index("time")
                if label1[2] != "Volume" and label1[2] != "Amount":
                    price_df = array_bfr["price"].resample(optInterval).ohlc(
                    )  # resample重新取样,选出ohlc=open/high/low,提取除价格之外另外4列.close,tushare是ohcl
                    price_df = price_df.dropna()
                    array = price_df
                    time = price_df.index.format()

                elif label1[2] == "Volume":
                    vols = array_bfr["volume"].resample(optInterval).sum(
                    )  #resample重新取样,累加间隔内数值 relevant data processing algorithm taken from Jimmy, Creator of Tushare
                    vols = vols.dropna()
                    vol_df = pd.DataFrame(vols, columns=["volume"])
                    array = vol_df
                    time = vol_df.index.format()
                else:
                    amounts = array_bfr["amount"].resample(optInterval).sum()
                    amounts = amounts.dropna()
                    amount_df = pd.DataFrame(amounts, columns=["amount"])
                    array = amount_df
                    time = amount_df.index.format()

            #绘图方法

            if label1[2] == 'Kline':
                re_array = array[['open', 'close', 'high', 'low']]
                data_li = list(row.tolist()
                               for index, row in re_array.iterrows()
                               )  # data_list = list(re_array.as_matrix())
                close = array['close'].tolist()
                kline = Kline(label1[0] + "-" + optInterval,
                              width=width1 * 10 / 11,
                              height=(height1 * 10 / 11) / len(labels))
                kline.add(label1[0],
                          time,
                          data_li,
                          is_datazoom_show=True,
                          datazoom_type="slider",
                          yaxis_interval=1)
                overlap.add(kline)

                if len(close) > 10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(label1[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close) > 20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(label1[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close) > 30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(label1[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)

                page.add(overlap)
            else:  #When label1[2]==open/close/volume
                if label1[2] == 'Open':
                    list_aft = array['open'].tolist()
                elif label1[2] == 'Close':
                    list_aft = array['close'].tolist()
                elif label1[2] == 'High':
                    list_aft = array['high'].tolist()
                elif label1[2] == 'Low':
                    list_aft = array['low'].tolist()
                elif label1[2] == 'Volume':  #volume
                    list_aft = array['volume'].tolist()
                else:  #amount
                    list_aft = array['amount'].tolist()

                line = Line(label1[0] + "-" + label1[2],
                            width=width1 * 10 / 11,
                            height=(height1 * 10 / 11) / len(labels))
                line.add(label1[0] + "-" + label1[2],
                         time,
                         list_aft,
                         is_datazoom_show=True,
                         yaxis_max="dataMax",
                         yaxis_min="dataMin",
                         datazoom_type="slider")
                overlap.add(line)
                page.add(overlap)

        elif label1[2] == "分笔":
            array = ts.get_tick_data(label1[1], date=startdate)
            array = array.sort_values("time")
            date = array["time"].tolist()
            amount = array["amount"].tolist()
            atype = array["type"].tolist()
            price = array["price"].tolist()
            flag = ["bar" for i in date]
            for idx, val in enumerate(atype):
                if val == "卖盘":
                    amount[idx] = -amount[idx]
                if val == "中性盘":
                    amount[idx] = 0

            returnarray = list(zip(date, amount, flag, price))

            form = [e[1] for e in returnarray]
            time = [d[0] for d in returnarray]

            bar = Bar(label1[0] + "-" + label1[2],
                      width=width1 * 10 / 11,
                      height=(height1 * 10 / 11) / len(labels))
            bar.add(label1[0] + "-" + label1[2],
                    time,
                    form,
                    is_datazoom_show=True,
                    datazoom_type="slider",
                    yaxis_min="dataMin",
                    yaxis_max="dataMax")
            overlap.add(bar)

            line = Line(label1[0] + "price",
                        width=width1 * 10 / 11,
                        height=(height1 * 10 / 11) / len(labels))
            price = [e[3] for e in returnarray]
            line.add(label1[0] + "price",
                     time,
                     price,
                     yaxis_min="dataMin",
                     yaxis_max="dataMax",
                     is_datazoom_show=True,
                     datazoom_type="slider",
                     yaxis_type="value")
            overlap.add(line, yaxis_index=1, is_add_yaxis=True)
            page.add(overlap)
        elif label1[2] == "季度饼图":
            datestr = startdate.split("-")
            thisyear = datestr[0]
            df2 = ts.top10_holders(code=label1[1], gdtype="1")
            test = df2[1]["quarter"].tolist()
            df_ready = df2[1]
            idxlist = []
            for idx, val in enumerate(test):
                a = val.split("-")
                if a[0] == thisyear:
                    # print a[0],idx
                    idxlist.append(idx)
            thing = df_ready.loc[idxlist]
            thing = thing.sort_values(["quarter", "name"])
            # print a[0],id
            name = thing["name"].tolist()
            value = thing["hold"].tolist()
            quarter = thing["quarter"].tolist()
            namearray = [name[i:i + 10] for i in range(0, len(name), 10)]
            valuearray = [value[j:j + 10] for j in range(0, len(value), 10)]
            quarterarray = [
                quarter[k:k + 10] for k in range(0, len(quarter), 10)
            ]

            flag = ["pie" for i in namearray]
            num = [len(value) for k in namearray]
            returnarray = list(
                zip(namearray, valuearray, quarterarray, flag, num))

            timeline = Timeline(is_auto_play=False, timeline_bottom=0
                                )  # zip(namearray,valuearray,quarter,flag,num)
            namearray = [c[0] for c in returnarray]
            valuearray = [d[1] for d in returnarray]
            quarter = [e[2] for e in returnarray]
            num = returnarray[0][4]

            for x in range(0, int(num / 10)):
                list1 = valuearray[x]
                names = namearray[x]
                quarters = quarter[x][0]

                for idx, val in enumerate(list1):
                    list1[idx] = float(val)

                pie = Pie(label1[0] + "-" + "前十股东",
                          width=width1 * 10 / 11,
                          height=(height1 * 10 / 11))

                pie.add(label1[0] + "-" + "前十股东",
                        names,
                        list1,
                        radius=[30, 55],
                        is_legend_show=False,
                        is_label_show=True,
                        label_formatter="{b}: {c}\n{d}%")
                timeline.add(pie, quarters)
                # namearray = [y for y in namearray[x]]
            timeline.render()

    page.render()