Exemplo n.º 1
0
def genPiePicture(df_score):
    # 导入Pie组件,用于生成饼图
    from pyecharts import Pie

    # 设定五个等级的星级标签
    attr = ["一星", "二星", "三星", "四星", "五星"]
    score = df_score.groupby("评分").size()  # 分组求和
    # print(score)

    value = [
        score.iloc[0] + score.iloc[1] + score.iloc[2],  # 0,0.5,1分均定为一星
        score.iloc[3] + score.iloc[4],  # 1.5,2分均定位二星
        score.iloc[5] + score.iloc[6],  # 2.5,3分均定为三星
        score.iloc[7] + score.iloc[8],  # 3.5,4分均定为四星
        score.iloc[9] + score.iloc[10],  # 4.5,5分均定为五星
    ]

    # 利用Pie模块,数据可视化
    pie = Pie('《流浪地球》评星比例', title_pos='left', width=1000, height=500)
    pie.use_theme("dark")
    pie.add("评分",
            attr,
            value,
            center=[60, 60],
            radius=[25, 75],
            rosetype='raea',
            is_legend_show=True,
            is_label_show=True)
    pie.render('评星.html')
    return pie
Exemplo n.º 2
0
def Length_of_sente():
    with open('./Love_words.txt','r', encoding='utf-8') as f:
        lines = f.readlines()
    data = pd.Series(np.array([len(line) for line in lines]))
    print(len(data))
    print(data.describe())
    bins = [i for i in range(0,201,20)]
    lengths = pd.cut(np.array([len(line) for line in lines]),bins=bins)
    # print(len(lengths))
    c = Counter(lengths)
    lengths = [i[0] for i in c.most_common(10)]
    lengths_num = [i[1] for i in c.most_common(10)]
    # print(words)
    # print(words_num)
    print(lengths)
    print(lengths_num)
    print(c.most_common())
    pie = Pie('句长统计', title_pos='best')
    pie.use_theme('dark')
    # pie.add(
    #     '句长统计',
    #     lengths,
    #     lengths_num,
    #     legend_pos='best',
    #     is_legend_show=False,
    #     is_label_show=True

    # )
    pie.render('句长.html')
Exemplo n.º 3
0
def show840Pie(dictData, renderAlone):
    """
    840饼图,待完善
    dictData:{'A':2,'B':3,...}
    renderAlone:是否单独渲染
    """
    pie = Pie('840刷新报表',
              '平均值饼图',
              title_pos='center',
              width=1600,
              height=900,
              page_title='840刷新报表')
    x_axis = tuple(dictData.keys())
    y_axis = tuple(dictData.values())
    pie.add('840刷新报表',
            x_axis,
            y_axis,
            legend_orient="vertical",
            legend_pos='left',
            rosetype='radius',
            radius=[30, 70],
            is_more_utils=True,
            is_label_show=True)
    # 其他主题:vintage,macarons,infographic,shine,roma
    pie.use_theme('vintage')
    if renderAlone:
        pie.render('840-pie-{}.html'.format(time.strftime('%Y%m%d%H%M%S')))
    else:
        return pie
Exemplo n.º 4
0
def day_loan_income():
    '''生成日放款收入图表'''

    # X轴label
    attr = ["产品A", "产品B", "产品C", "产品D", "产品E", "产品F"]

    # 图表数据
    v1 = list(np.random.randint(200, 1000, 6) / 10)

    # 生成图表实例
    chart = Pie(
        "今日收入(单位:万)",
        "今日总收入为%f万" % np.sum(v1),
        background_color=BACKGROUND_COLOR,
        width="100%")

    # 使用暗色主题
    chart.use_theme('dark')

    # 载入默认设置并差异化更新
    chart_kwargs = DEFAULT_KWARGS
    chart_kwargs.update({})

    # 添加数据
    chart.add("收入", attr, v1, **chart_kwargs)

    return chart
Exemplo n.º 5
0
def analysisFrequency_Pie():
    # 使用cursor()方法获取操作游标
    conn = getConnection()
    cursor = conn.cursor()

    try:
        # 执行SQL语句
        cursor.execute('CALL Proc_HitTimes()')
        # 获取所有记录列表
        results = cursor.fetchall()

        textList = []
        valueList = []
        for row in results:
            textList.append(row['OpenNumber'])
            valueList.append(row['OpenNumberCount'])

        pie = Pie()
        pie.use_theme('dark')
        pie.add("命中次数",
                textList,
                valueList,
                '55%', ['50%', '60%'],
                roseType='area',
                is_label_show=True)

        pie.render()
    except Exception as queryError:
        print(queryError)
    finally:
        conn.close()
Exemplo n.º 6
0
def drawPie(title, data, savepath='./results'):
	if not os.path.exists(savepath):
		os.mkdir(savepath)
	pie = Pie(title, title_pos='center')
	pie.use_theme('westeros')
	attrs = [i for i, j in data.items()]
	values = [j for i, j in data.items()]
	pie.add('', attrs, values, is_label_show=True, legend_orient="vertical", legend_pos="left", radius=[30, 75], rosetype="area")
	pie.render(os.path.join(savepath, '%s.html' % title))
 def analysisSex(self):
     title = 'Gender Analysis'
     data = {'Male': 0, 'Female': 0, 'Confidential': 0}
     pie = Pie(title, title_pos='center')
     pie.use_theme('westeros')
     for each in self.friends_info.get('sex'):
         if each == 0:
             data['Confidential'] += 1
         elif each == 1:
             data['Male'] += 1
         elif each == 2:
             data['Female'] += 1
     attrs = [i for i, j in data.items()]
     values = [j for i, j in data.items()]
     pie.add('',
             attrs,
             values,
             is_label_show=True,
             legend_orient="vertical",
             legend_pos="left",
             radius=[30, 75],
             rosetype="area")
     pie.render(os.path.join(self.savedir, '%s.html' % title))
Exemplo n.º 8
0
def chart_view03():
    # 从mongo中获取数据
    (x, y) = BidNotice.get_records_group_by_notice_type()

    # 设置bar图形的基本属性
    pie = Pie("公告类型分析图", "From: cmccb2b")
    pie.use_theme('light')
    pie.add("公告类型", x, y, is_stack=False)  # 从Mongo读取的数据存放在这里

    javascript_snippet = TRANSLATOR.translate(pie.options)  # 将bar的属性设置翻译为js脚本
    # pie.print_echarts_options()                  # 该行只为了打印配置项,方便调试时使用

    return render_template(
        "pyecharts.html",  # 自定义,位于templates/的模版文件
        chart_id=pie.chart_id,  # 默认设置,
        host=REMOTE_HOST,  # 常量定义,存放js文件的url地址
        renderer=pie.renderer,  # 默认设置,
        my_width="100%",  # 默认设置,定义图表的宽度
        my_height=600,  # 默认设置,定义图表的高度
        custom_function=javascript_snippet.
        function_snippet,  # 默认设置,保存图片的方法,似乎基于node.js
        options=javascript_snippet.option_snippet,  # 默认设置,
        script_list=pie.get_js_dependencies(),  # 默认设置,需要动态加载的js文件
    )
Exemplo n.º 9
0
tokens=[token for token in cun if token not in stops]
d={}
for i in tokens:
    d[i] = d.get(i,0) + 1

count_list = sorted(d.items(), key=lambda x:x[1], reverse=True)
count_list = count_list[:20]
keyword_list = [k[0] for k in count_list]
value_list = [k[1] for k in count_list]


attr = keyword_list
v1 = value_list
#v2 = [19, 21, 32, 20, 20, 33]
pie =Pie(background_color='#404a59')
pie.use_theme('dark')
#pie.add("学历", attr, v1, center=[25, 50], is_random=True, radius=[20, 60], rosetype='radius')
pie.add("学历", attr, v1, is_random=True, radius=[20, 60], is_legend_show=False, is_label_show=True)
pie.show_config() 
#pie.render(r"D:\BI大屏\学历需求饼图.html")
page.add_chart(pie,name="pie") 

#=============================================================================
# 工作经验折线图
import pandas as pd
from pyecharts import Line
#=============================================================================

#导入文本
a = []
txt1 = pd.read_excel(r'D:\BI大屏\拉勾网.xlsx')
Exemplo n.º 10
0
    def display(self):
        self.radioButton.setChecked(True)
        conn = pymysql.connect(host='127.0.0.1',
                               user='******',
                               passwd='714511',
                               db='qinwenrui',
                               port=3306,
                               charset='utf8mb4')

        year = self.comboBox_2.currentText().replace(' ', '')
        month = self.comboBox_4.currentText().replace(' ', '')  #输入

        sql = 'SELECT * FROM `dianying`;'
        df = pd.read_sql(sql, conn)
        if year != '所有年份':
            a = df[(df.年份 == year) & (df.月份 == int(month))]
        else:
            a = df[(df.月份 == int(month))]

        M = []
        TYPE = a[['题材', '票房']]
        c = TYPE[(TYPE.题材 == '犯罪')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '喜剧')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '剧情')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '纪录片')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '奇幻')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '动作')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '冒险')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '悬疑')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '动画')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '战争')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '家庭')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '科幻')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '历史')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        #TYPE.loc[rows]获取信息
        tp = [
            '犯罪', '喜剧', '剧情', '纪录片', '奇幻', '动作', '冒险', '悬疑', '动画', '战争', '家庭',
            '科幻', '历史'
        ]

        pie = Pie('{}年{}月题材票房占比'.format(year, month),
                  title_pos='center',
                  width=907,
                  height=619)  #h=625
        pie._option['animation'] = False
        pie.use_theme('dark')
        pie.add('',
                tp,
                M,
                center=[50, 50],
                radius=[0, 60],
                is_label_show=True,
                legend_orient='vertical',
                legend_pos='left')
        pie.render('./graph/monthtype.html')
        self.widget.load(QUrl.fromLocalFile('/graph/monthtype.html'))
Exemplo n.º 11
0
def draw_pic(data, title, type_):
    title = title + '成绩分布图'
    list_1 = [0, 0, 0, 0, 0]
    for i in data:
        if i >= 0 and i < 60:
            list_1[0] += 1
        elif i >= 60 and i < 70:
            list_1[1] += 1
        elif i >= 70 and i < 80:
            list_1[2] += 1
        elif i >= 80 and i < 90:
            list_1[3] += 1
        elif i >= 90 and i < 100:
            list_1[4] += 1
    attr = ['60以下', '60~70', '70~80', '80~90', '90~100']
    if type_ == 'pie':
        pie = Pie(title=title, height=582, width=880)
        pie.use_theme('dark')
        pie.add("人数",
                attr,
                list_1,
                is_more_utils=True,
                radius=[40, 75],
                is_legend_show=True,
                is_label_show=True,
                rosetype='area')
        pie.render()

    elif type_ == 'bar':
        bar = Bar(title=title, height=582, width=880)
        bar.use_theme('dark')
        bar.add("人数",
                attr,
                list_1,
                is_more_utils=True,
                mark_line=['average'],
                mark_point=['min', 'max'])
        bar.render()

    elif type_ == 'bar3D' or type_ == 'bar3d':
        dot_set = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]
        dot_set = [[x[0], x[1]] for x in dot_set]
        for i in range(5):
            dot_set[i].append(list_1[i])
        max_ = 1.4 * max(list_1)
        range_color = [
            '#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf',
            '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026'
        ]
        bar = Bar3D(title, height=582, width=880)
        # bar.use_theme('dark')
        # for x in dot_set:
        #     print(x[2])
        bar.add("", ['低于60分', '60~70', '70~80', '80~90', '90~100'], [0],
                [[x[0], x[1], x[2]] for x in dot_set],
                is_visualmap=True,
                visual_range=[0, max_],
                grid3d_width=100,
                visual_range_color=range_color,
                grid3d_depth=25,
                is_more_utils=True)
        bar.render()
Exemplo n.º 12
0
    def draw_bar(self, dbName, begDate=None):
        Beg, End = self.get_date_begin_end()
        if begDate == None:
            begDate = Beg[0]
        maxvalue = get_days(begDate, End[0])
        data1 = self.__get_draw_bar_data_core__(dbName, begDate, ('<', 50))
        dataBase = self.__get_draw_bar_data_core__(dbName, begDate, ('<', 100))
        data3 = self.__get_draw_bar_data_core__(dbName, begDate, ('<', 150),
                                                ('>=', 100))  #轻度
        data4 = self.__get_draw_bar_data_core__(dbName, begDate, ('<', 200),
                                                ('>=', 150))
        data5 = self.__get_draw_bar_data_core__(dbName, begDate, ('<', 300),
                                                ('>=', 200))
        data6 = self.__get_draw_bar_data_core__(dbName, begDate, ('>=', 300))

        count = max(len(data1), len(dataBase), len(data3), len(data4),
                    len(data5), len(data6))
        # print(len(data1),len(dataBase),len(data3),len(data4),len(data5),len(data6))
        valueBase, nameBase = self.__get_value_name_bar__(dataBase, count)

        def __re_arrange(count, nameBase, dataInput):
            valuetemp = count * [0]
            idx = 0
            for item in nameBase:
                for i in dataInput:
                    if item == i[1]:
                        valuetemp[idx] = i[0]
                        break
                idx = idx + 1
            return valuetemp

        def label_formatter(params):
            return params.name + ' ' + str(params.value) + '%'

        grid = Grid(**style2.init_style)
        grid.use_theme("dark")
        bar = Bar("", **style1.init_style)
        value1 = __re_arrange(count, nameBase, data1)
        bar.add("优", nameBase[:-1], value1[:-1], is_stack=True)
        # list(map(lambda x: x[0]-x[1], zip(valueBase, valuetemp)))
        bar.add("良",
                nameBase[:-1],
                list(
                    map(lambda x: x[0] - x[1] - x[2],
                        zip(valueBase[:-1], value1[:-1], count * [3]))),
                is_stack=True)
        value3 = __re_arrange(count, nameBase, data3)
        bar.add("轻度污染", nameBase[:-1], value3[:-1], is_stack=True)
        value4 = __re_arrange(count, nameBase, data4)
        bar.add("中度污染", nameBase[:-1], value4[:-1], is_stack=True)
        value5 = __re_arrange(count, nameBase, data5)
        bar.add("重度污染", nameBase[:-1], value5[:-1], is_stack=True)
        value6 = __re_arrange(count, nameBase, data6)
        bar.add(
            "严重污染",
            nameBase[:-1],
            value6[:-1],
            is_stack=True,
            # yaxis_name="天",
            # yaxis_name_size='16',
            # yaxis_name_gap='25',
            # yaxis_name_pos='top',
            xaxis_type="category",
            xaxis_interval=0,
            yaxis_interval=0,
            xaxis_pos='top',
            yaxis_max=maxvalue,
            # is_label_show=True,
            #bar_category_gap="30%",
            xaxis_label_textsize=12,
            yaxis_label_textsize=12,
            xaxis_rotate=90,
            yaxis_rotate=90,
            # label_formatter=label_formatter,
            is_legend_show=True,
            legend_pos='91%',
            legend_top='center',
            legend_orient='horizontal',
            label_pos='bottom',
            label_text_size=16,
            label_color=[
                '#43CE17', '#EFDC31', '#FFAA00', '#FF401A', '#D20040',
                '#9C0A4E'
            ])

        idxList = [str(x) for x in range(1, len(valueBase))]
        line = Line()
        meanList = len(idxList) * [sum(valueBase[:-1]) / len(idxList)]
        line.add("",
                 idxList,
                 meanList,
                 line_width=3,
                 symbol=None,
                 line_color='#0078D7',
                 mark_line=["average"])
        line.add("",
                 idxList,
                 valueBase[:-1],
                 is_smooth=True,
                 symbol=None,
                 line_width=3,
                 xaxis_label_textsize=16,
                 xaxis_rotate=90,
                 line_color='#FF401A')
        overlap = Overlap()
        overlap.add(bar)
        overlap.add(line, is_add_xaxis=True, xaxis_index=1)
        grid.add(overlap, grid_top="21%")
        grid.render()
        grid.render("最优城市排行榜.jpeg")

        #低于均值城市的饼状图

        lowThanMeanDic = {}
        for v in nameBase[-101:-1]:
            # if v < meanList[0]:
            key = v.split('-')[1]
            if key in lowThanMeanDic.keys():
                lowThanMeanDic[key] = lowThanMeanDic[key] + 1
            else:
                lowThanMeanDic[key] = 1
        data = self.__sort_by_value__(lowThanMeanDic)
        value, name = self.__get_value_name_bar__(data, len(data))
        pie = Pie()
        pie.use_theme("dark")
        pie.add("",
                name,
                value,
                is_legend_show=False,
                is_label_show=True,
                label_text_size=10)
        pie.render("最污百城省份分布.jpeg")