def image_host_resource(doc_path, hosts_metrics, host):
    options = opts.InitOpts(js_host=os.path.join(os.getcwd(), "scripts/javascript/"),
                            animation_opts=opts.AnimationOpts(animation=False))
    line1 = (
        Line(options)
            .add_xaxis(hosts_metrics[host['ip']]['metrics']['datetime'])
            .add_yaxis("CPU", hosts_metrics[host['ip']]['metrics']['cpu'], is_symbol_show=False, is_smooth=True,
                       areastyle_opts=opts.AreaStyleOpts(color=utils.JsCode(
                           "new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'rgb(255,158,68)'},{offset:1,color:'rgb(255,70,131)'}])"),
                           opacity=0.5))
            .add_yaxis("Memory", hosts_metrics[host['ip']]['metrics']['memory'], is_symbol_show=False, is_smooth=True)
            .set_series_opts(linestyle_opts=opts.LineStyleOpts(width=2))
            .set_global_opts(
            title_opts=opts.TitleOpts(title="主机资源使用率 (%s)" % (host['ip']),
                                      title_textstyle_opts=opts.TextStyleOpts(font_size=13),
                                      subtitle=" 数据来源-健康度平台"),
            xaxis_opts=opts.AxisOpts(type_="time"),
            yaxis_opts=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(formatter=utils.JsCode("function(val){return val + '%';}")))
        )
    )

    line2 = (
        Line(options)
            .add_xaxis(hosts_metrics[host['ip']]['metrics']['datetime'])
            .add_yaxis("Process", hosts_metrics[host['ip']]['metrics']['process'], is_symbol_show=False, is_smooth=True,
                       areastyle_opts=opts.AreaStyleOpts(color=utils.JsCode(
                           "new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'#fff'},{offset:1,color:'#61a0a8'}])"),
                           opacity=0.5)
                       )
            .set_series_opts(linestyle_opts=opts.LineStyleOpts(width=2))
            .set_global_opts(
            xaxis_opts=opts.AxisOpts(type_="time", position="top", axislabel_opts=opts.LabelOpts(is_show=False)),
            yaxis_opts=opts.AxisOpts(is_inverse=True),
            title_opts=opts.TitleOpts(title="应用运行数量(所有)", pos_bottom="0%",
                                      title_textstyle_opts=opts.TextStyleOpts(font_size=13)),
            legend_opts=opts.LegendOpts(pos_bottom="0%")
        )
    )

    grid = (
        Grid(options)
            .add(line1, grid_opts=opts.GridOpts(pos_top=50, pos_left=50, pos_right=50, pos_bottom="50%"))
            .add(line2, grid_opts=opts.GridOpts(pos_top="58%", pos_left=50, pos_right=50, pos_bottom=30))
    )

    make_snapshot(snapshot, grid.render(os.path.join(doc_path, "render_%s.html" % (host['ip'].replace(".", "_")))),
                  os.path.join(doc_path, "host_res_%s.png" % (host['ip'].replace(".", "_"))), pixel_ratio=1, delay=1,
                  is_remove_html=True)
Exemple #2
0
	def map_visualmap(area_list, job_num_list) -> Map:
		c = (
			Map(init_opts=opts.InitOpts(theme=ThemeType.ROMA,))
			.add(
				"",
				[list(z) for z in zip(area_list, job_num_list)],
				"china",

				tooltip_opts = opts.TooltipOpts(formatter=utils.JsCode(
					"""function (params){
						return params.name + ' : ' + params.value + '<br/>';
					}"""
					))
			)
			.set_global_opts(
				title_opts=opts.TitleOpts(title="{}岗位全国热度一览".format(jobkey)),
				legend_opts = opts.LegendOpts(pos_left = 'center',),
				visualmap_opts=opts.VisualMapOpts(  # 视觉映射配置项
					is_piecewise=True,  # 是否分段
					max_= max(job_num_list),  # 分段的最大值
					# 自定义分段信息
					pieces = [
						{"min": 0, "max": int(max(job_num_list)/5), "color": "steelblue"},
						{"min": int(max(job_num_list)/5), "max": int(max(job_num_list)/5)*2},
						{"min": int(max(job_num_list)/5)*2, "max": int(max(job_num_list)/5)*3},
						{"min": int(max(job_num_list)/5)*3, "max": int(max(job_num_list)/5)*4},
						{"min": int(max(job_num_list)/5)*4, "max": max(job_num_list)},
					]
				)
			)
		)
		return c
 def bar(self,df,legend,title,path):
     '''
     柱状图
     :param df: 要操作的数据
     :param legend: 图例
     :param title: 报表标题
     :param path: 保存路径
     :return:
     '''
     tmp = df.value_counts()
     x = list(tmp.index)
     y = list(tmp)
     bar = Bar()
     bar.add_xaxis(x)
     bar.add_yaxis(legend, y, category_gap="60%")
     bar.set_series_opts(itemstyle_opts={
         "normal": {
             "color": utils.JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                         offset: 0,
                         color: 'rgba(0, 244, 255, 1)'
                     }, {
                         offset: 1,
                         color: 'rgba(0, 77, 167, 1)'
                     }], false)"""),
             "barBorderRadius": [30, 30, 30, 30],
             "shadowColor": 'rgb(0, 160, 221)',
         }})
     bar.set_global_opts(title_opts=opts.TitleOpts(title=title))
     bar.render(path + '/' + title + '.html')
def make_scatter1(x, y, name, fill_color, border_color):
    '''制作基本元素周期表'''
    p = (Scatter().add_xaxis(x).add_yaxis(
        name,
        y,
        symbol="rect",
        symbol_size=[50, 50],
        label_opts=opts.LabelOpts(is_show=True,
                                  position="insideLeft",
                                  formatter=utils.JsCode('''function(params){
                return ['{an_s|'+params.value[2]+' '+params.value[3]+'}',
                        '{n|'+params.value[4]+'}',
                        '{am|'+params.value[5]+'}'
                        ].join('\\n')
                        }'''),
                                  rich={
                                      "an_s": {
                                          "fontSize": 11,
                                          "color": "black",
                                          "textBorderWidth": 0
                                      },
                                      "n": {
                                          "fontSize": 20,
                                          "fontWeight": "bold",
                                          "color": "black",
                                          "textBorderWidth": 0
                                      },
                                      "am": {
                                          "fontSize": 7,
                                          "color": "black",
                                          "textBorderWidth": 0
                                      }
                                  }),
        itemstyle_opts=opts.ItemStyleOpts(color=fill_color,
                                          border_color=border_color,
                                          border_width=1),
        tooltip_opts=opts.TooltipOpts(
            is_show=True,
            formatter=utils.JsCode('''function(params){
                return ['元素序号:'+params.value[2],
                        '元素名称:'+params.value[4],
                        '元素符号:'+params.value[3],
                        '元素族类:'+params.seriesName,
                        '相对原子质量:'+params.value[5]
                        ].join('<br/>')
                        }'''))))
    return p
def make_scatter3():
    '''制作镧系锕系元素周期表'''
    p = (Scatter().add_xaxis(list(range(0, 15)) * 2).add_yaxis(
        "过渡金属",
        [data_lana.loc[i, "period":].to_list() for i in data_lana.index],
        symbol="rect",
        symbol_size=[50, 50],
        label_opts=opts.LabelOpts(is_show=True,
                                  position="insideLeft",
                                  formatter=utils.JsCode('''function(params){
                return ['{an_s|'+params.value[2]+' '+params.value[3]+'}',
                        '{n|'+params.value[4]+'}',
                        '{am|'+params.value[5]+'}'
                        ].join('\\n')
                        }'''),
                                  rich={
                                      "an_s": {
                                          "fontSize": 11,
                                          "color": "black",
                                          "textBorderWidth": 0
                                      },
                                      "n": {
                                          "fontSize": 20,
                                          "fontWeight": "bold",
                                          "color": "black",
                                          "textBorderWidth": 0
                                      },
                                      "am": {
                                          "fontSize": 7,
                                          "color": "black",
                                          "textBorderWidth": 0
                                      }
                                  }),
        itemstyle_opts=opts.ItemStyleOpts(color=color_map["过渡金属"][0],
                                          border_color=color_map["过渡金属"][1],
                                          border_width=1),
        tooltip_opts=opts.TooltipOpts(
            is_show=True,
            formatter=utils.JsCode('''function(params){
                return ['元素序号:'+params.value[2],
                        '元素名称:'+params.value[4],
                        '元素符号:'+params.value[3],
                        '元素族类:'+params.seriesName,
                        '相对原子质量:'+params.value[5]
                        ].join('<br/>')
                        }'''))))
    return p
def make_scatter2():
    '''填补镧系锕系元素的空格'''
    p = (Scatter().add_xaxis([2, 2]).add_yaxis(
        "过渡金属",
        [["Ⅵ", "57-71", "La-Lu", "镧系"], ["Ⅶ", "89-103", "Ac-Lr", "锕系"]],
        symbol="rect",
        symbol_size=[50, 50],
        label_opts=opts.LabelOpts(is_show=True,
                                  position="insideLeft",
                                  formatter=utils.JsCode('''function(params){
                return ['{an|'+params.value[2]+'}',
                        '{s|'+params.value[3]+'}',
                        '{n|'+params.value[4]+'}'
                        ].join('\\n')
                        }'''),
                                  rich={
                                      "an": {
                                          "fontSize": 11,
                                          "color": "red",
                                          "textBorderWidth": 0
                                      },
                                      "s": {
                                          "fontSize": 11,
                                          "color": "red",
                                          "textBorderWidth": 0
                                      },
                                      "n": {
                                          "fontSize": 20,
                                          "fontWeight": "bold",
                                          "color": "red",
                                          "textBorderWidth": 0
                                      }
                                  }),
        itemstyle_opts=opts.ItemStyleOpts(color=color_map["过渡金属"][0],
                                          border_color=color_map["过渡金属"][1],
                                          border_width=1),
        tooltip_opts=opts.TooltipOpts(
            formatter=utils.JsCode('''function(params){
                    return params.value[4]
                }'''))))
    return p
 def __init__(self, title: str, output: str):
     self.title = title
     self.output = output
     self.datas = []
     self.chart = (Line(init_opts=opts.InitOpts(
         page_title=self.title,
         theme=ThemeType.DARK,
         width="1280px",
         height="720px",
     )).set_global_opts(
         title_opts=opts.TitleOpts(title=self.title),
         xaxis_opts=opts.AxisOpts(type_="value",
                                  is_scale=True,
                                  split_number=10,
                                  name="bitrate/kbps"),
         yaxis_opts=opts.AxisOpts(type_="value", is_scale=True,
                                  name="vmaf"),
         toolbox_opts=opts.ToolboxOpts(
             is_show=True,
             orient="vertical",
             pos_left="right",
             feature=opts.ToolBoxFeatureOpts(
                 save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(
                     title="save as image", is_show=True),
                 restore=opts.ToolBoxFeatureRestoreOpts(is_show=False),
                 data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False),
                 data_view=opts.ToolBoxFeatureDataViewOpts(
                     is_show=False, is_read_only=True, title="data"),
                 magic_type=opts.ToolBoxFeatureMagicTypeOpts(is_show=False),
                 brush=opts.ToolBoxFeatureBrushOpts(type_=[]))),
         legend_opts=opts.LegendOpts(pos_top="bottom"),
         tooltip_opts=opts.TooltipOpts(
             is_show=True,
             formatter=pyecharts_utils.JsCode(
                 "function(x) {return x.seriesName + '<br/>bitrate&nbsp;&nbsp;'+ x.data[0] + '&nbsp;kbps<br/>vmaf&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + x.data[1];}"
             ))))
def timeline_map() -> Timeline:
    allMaps = []

    # 共有 12 个地图
    for (months, index) in zip(yearMonth, range(0, 11)):
        
        # 计算得出当前颜色域的范围, 根据个数平均分成10个组。
        sliptNum = int(len(list(np.array(rowData)[:,index+1])) / 10)
        splitBoundaryIndex = [i for i in range(0, len(list(np.array(rowData)[:,index+1])), sliptNum)]
        splitBoundaryIndex.append(len(list(np.array(rowData)[:,index+1])) - 1)   # 以防万一,将最后一个也加进去。
        tmpSort = [int(i) for i in list(np.array(rowData)[:,index+1])]
        tmpSort.sort()
        splitBoundary = [tmpSort[i] for i in splitBoundaryIndex]                 # ex: [1, 4, 9, 16, 33, 54, 125, 201, 317, 538, 2663]
        # 转化为 json
        jsonSplitBoundary = '['
        for i in range(len(splitBoundary) - 1):
            jsonSplitBoundary += "{\"min\": " + str(splitBoundary[i]) + ", \"max\": " + str(splitBoundary[i+1]) + "},"
        jsonSplitBoundary +='$]'
        jsonSplitBoundary = jsonSplitBoundary.replace(",$", "")
        jsonSplitBoundary = json.loads(jsonSplitBoundary)

        map = (
            Geo()
            .add_schema(maptype="四川+重庆")
            .add_coordinate_json(
                json_file='./myjson.json'
            )   
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="实验四-每月的销售最高Brand-county"),
                # list 转 int, 获取 max range, min default 0
                visualmap_opts=opts.VisualMapOpts(
                    max_= max([int(x) for x in list(np.array(rowData)[:,index+1])]),
                    is_piecewise=True,
                    pieces = jsonSplitBoundary
                ),
            )
        )
        # 通过地点 name 与 该点的数值 添加地理点
        # 这里通过循环遍历、因为他这个我真的没办法添加品牌。。。,这里用 series_name 来存放 brand
        for z in zip(list(np.array(rowData)[:,0]), list(np.array(rowData)[:,index+1]), list(np.array(rowBrand)[:,index+1])):
            map.add(
                series_name = z[2],
                data_pair = [list(z[0:2])],
                type_=ChartType.EFFECT_SCATTER,
                large_threshold = 2000,
                label_opts = opts.LabelOpts(formatter = utils.JsCode("""
                function (params) {
                    return params.seriesName
                }
                """)
                )
            )
        allMaps.append(map)
    # 将allMaps 与时间轴绑定
    tl = (
        Timeline().add_schema(
            play_interval = 2000,
            is_auto_play = True
        )
    )
    for (itemTime, itemMap) in zip(yearMonth, allMaps):
        tl.add(itemMap, itemTime)

    return tl
Exemple #9
0
def test_js_code():
    fn = "function() { console.log('test_js_code') }"
    js_code = utils.JsCode(fn)
    assert_equal(js_code.js_code, "--x_x--0_0--{}--x_x--0_0--".format(fn))
Exemple #10
0
    def pyechart_Graph_plot(self, filedata, para):  # 指定文件名,包括扩展名
        from pyecharts.charts import Graph
        from pyecharts.globals import CurrentConfig
        print(CurrentConfig.ONLINE_HOST)

        file_name = '关系图.html'
        path_plotly = self.path_dir_plotly_html + os.sep + file_name  # 文件路径,前面是文件夹后面是文件名
        #print(path_plotly)
        costumeTheme = self.themedict[para['theme']]
        df = pd.read_excel(filedata, sheet_name='Sheet1')

        Ename = df['name'].dropna().values.tolist()

        Esource = df['source'].dropna().values.tolist()
        Etarget = df['target'].dropna().values.tolist()
        Elabel = df['relation'].dropna().values.tolist()
        Evalue = df['value'].dropna().values.tolist()
        print(Elabel)
        Esymbol_size = df['size'].dropna().values.tolist()
        Ecategory = df['category'].dropna().values.tolist()
        #print(Ecategory)
        nodes_data = []
        links_data = []
        category = []
        for i in range(0, len(Ename)):
            nodes_data.append({
                'name': Ename[i],
                'symbolSize': int(Esymbol_size[i]),
                'symbol':
                "circle",  ## ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none'
                'category': Ecategory[i]
            })
            category.append({'name': Ecategory[i]})
        #print(nodes_data)
        for i in range(0, len(Esource)):
            links_data.append({
                'source': Esource[i],
                'target': Etarget[i],
                'value': Evalue[i]
            })

        a = str(Elabel)
        GEO = "function (params) { a= " + a + ";return a[params.dataIndex];}"
        #GEO = "function (params) { return params.dataIndex;}"   #数据索引 #renderer为svg时清晰一点,但是无法保存为图片
        c = (
            Graph(init_opts=opts.InitOpts(theme=costumeTheme,
                                          renderer="canvs",
                                          width=para['width'],
                                          height=para['height']))  #
            .add(
                "",  #series_name, # 系列名称,用于 tooltip 的显示,legend 的图例筛选。
                nodes=nodes_data,
                links=links_data,
                categories=category,
                gravity=para["gravity"],
                repulsion=para["repulsion"],
                edge_symbol=["", "arrow"],  #可以单一指定
                is_draggable=True,  #允许拖动,只在力引导有用
                layout=para['layout'],  ## 'circular' 采用环形布局。# 'force' 采用力引导布局
                is_rotate_label=True,
                linestyle_opts=opts.LineStyleOpts(
                    color="source",
                    curve=0.3),  #标签在上方显示,以防止被遮挡 top/middle,edge的上方是箭头的起点
                label_opts=opts.LabelOpts(is_show=True,
                                          color=para["color"],
                                          position="top",
                                          font_size=para["font_size"],
                                          font_family=para["font_family"]),
                edge_label=opts.LabelOpts(is_show=True,
                                          color=para["color"],
                                          position="middle",
                                          font_size=para["font_size"],
                                          font_family=para["font_family"],
                                          formatter=utils.JsCode(GEO)),
            ))
        chart = c
        self.Common_code(chart, path_plotly, para)
        return path_plotly  # 返回该HTML文件路径