Exemple #1
0
def draw_power(request):
    start = request.GET.get('day')

    if not start:
        start = datetime.date.today()
    else:
        try:
            start = datetime.datetime.strptime(start, '%Y-%m-%d')
        except:
            start = datetime.date.today()
    end = start + datetime.timedelta(days=1)

    sql = "select time, voltage, current, rate, consumption from tbl_power where time>=%s and time<%s order by time"
    with connection.cursor() as c:
        c.execute(sql, (start, end))
        rows = c.fetchall()
    time_list, voltage_list, current_list, rate_list, consumption_list = [], [], [], [], []
    for time, voltage, current, rate, consumption in rows:
        time_list.append(time)
        voltage_list.append(voltage)
        current_list.append(current)
        rate_list.append(rate)
        consumption_list.append(consumption)

    c = (charts.Line().add_xaxis(time_list).add_yaxis(
        "电压", voltage_list).add_yaxis("电流", current_list).add_yaxis(
            "功率",
            rate_list).add_yaxis("累计耗电量", consumption_list).set_global_opts(
                title_opts=opts.TitleOpts(title="测试监控", subtitle="耗电基本信息")))
    return HttpResponse(c.render_embed())
Exemple #2
0
def index(request):
    c = (charts.Line().add_xaxis([i for i in range(1000)]).add_yaxis(
        "商家A", [random.randint(50, 100) for i in range(1000)]).add_yaxis(
            "商家B",
            [random.randint(1, 50) for i in range(1000)]).set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")))
    return HttpResponse(c.render_embed())
Exemple #3
0
def draw_action(request):
    start = request.GET.get('day')

    if not start:
        start = datetime.date.today()
    else:
        try:
            start = datetime.datetime.strptime(start, '%Y-%m-%d')
        except:
            start = datetime.date.today()
    end = start + datetime.timedelta(days=1)

    sql = "select time, yaw, pitch, roll, acc_x, acc_y, acc_z from tbl_door where time>=%s and time<%s order by time"
    with connection.cursor() as c:
        c.execute(sql, (start, end))
        rows = c.fetchall()
    time_list, yaw_list, pitch_list, roll_list, accx_list, accy_list, accz_list = [
        [] for _ in range(7)
    ]
    for time, yaw, pitch, roll, acc_x, acc_y, acc_z in rows:
        time_list.append(time)
        yaw_list.append(yaw)
        roll_list.append(roll)
        accx_list.append(acc_x)
        accy_list.append(acc_y)
        accz_list.append(acc_z)

    c = (charts.Line().add_xaxis(time_list).add_yaxis(
        "yaw", yaw_list).add_yaxis("pitch", pitch_list).add_yaxis(
            "roll", roll_list).add_yaxis(
                "x向加速度", accx_list).add_yaxis("y向加速度", accy_list).add_yaxis(
                    "z向加速度",
                    accz_list).set_global_opts(title_opts=opts.TitleOpts(
                        title="测试监控", subtitle="门的开关监控数据流")))
    return HttpResponse(c.render_embed())
Exemple #4
0
    def echarts(self):
        self._echarts_align_data()
        c = charts.Line()

        for k, v in self.curve_values.items():
            c.add_xaxis([str(i) for i in self.x_axis])
            break

        # max_v_dict = defaultdict(list)

        for _, v in self.curve_values.items():
            # max_v_dict[k].append([max(v[self.y_key]),min(v[self.y_key])])
            c.add_yaxis(
                v[self.name_key],
                v[self.y_key],
                label_opts=opts.LabelOpts(is_show=False),
                is_symbol_show=False,
            )

        c.set_global_opts(title_opts=opts.TitleOpts(
            title=self.title, padding=5),
            yaxis_opts=opts.AxisOpts(
                min_='dataMin',
                max_='dataMax',
            ),
            legend_opts=opts.LegendOpts(type_='scroll', pos_bottom=10),
            tooltip_opts=opts.TooltipOpts(is_show=True, trigger='axis'), )

        return c
Exemple #5
0
def draw_temperature(request):
    start = request.GET.get('day')

    if not start:
        start = datetime.date.today()
    else:
        try:
            start = datetime.datetime.strptime(start, '%Y-%m-%d')
        except:
            start = datetime.date.today()
    end = start + datetime.timedelta(days=1)

    sql = 'SELECT time, code, value FROM  tbl_temperature where time>=%s AND time<%s order by code, time'
    with connection.cursor() as c:
        c.execute(sql, (start, end))
        rows = c.fetchall()

    time_list = []
    lines = []

    for key, content in groupby(rows, key=lambda x: x[1]):
        if not time_list:
            values = []
            for time, _, value in content:
                time_list.append(time)
                values.append(value)
        else:
            values = [value for _, _, value in content]
        lines.append((layer_map[key], values))

    if len(lines) != 6:
        c = (charts.Line().add_xaxis(time_list).add_yaxis(
            "传感器异常", []).set_global_opts(
                title_opts=opts.TitleOpts(title="测试监控", subtitle="传感器温度信息")))
    else:
        c = (charts.Line().add_xaxis(time_list).add_yaxis(
            lines[0][0],
            lines[0][1]).add_yaxis(lines[1][0], lines[1][1]).add_yaxis(
                lines[2][0],
                lines[2][1]).add_yaxis(lines[3][0], lines[3][1]).add_yaxis(
                    lines[4][0], lines[4][1]).add_yaxis(
                        lines[5][0],
                        lines[5][1]).set_global_opts(title_opts=opts.TitleOpts(
                            title="测试监控", subtitle="传感器温度信息")))
    return HttpResponse(c.render_embed())
Exemple #6
0
def drawtable(request):
    json_data = request.body.decode('utf-8')
    info = json.loads(json_data)
    table_name = info.get('table_name', '').strip()

    # line_path = 'mycharts/render/tabledata/charts_%s.html' % table_name.split('.')[1]
    # 部署到apache服务器后需要使用绝对路径
    line_path = os.path.join(
        app_dir, 'render/tabledata/charts_%s.html' % table_name.split('.')[1])
    if not os.path.exists(
            line_path) or time.time() - os.path.getmtime(line_path) > 86400:
        table = get_object_or_404(TableData, table_name=table_name)
        line_name = table.table_name
        table_data = table.table_data
        x_data = table_data.get("total_diff_rate").keys()
        y_data = table_data.get("total_diff_rate").values()
        line = (charts.Line().set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=False),
            xaxis_opts=opts.AxisOpts(type_="category"),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            title_opts=opts.TitleOpts(
                title="差异比",
                subtitle="单位1")).add_xaxis(xaxis_data=x_data).add_yaxis(
                    series_name=line_name,
                    y_axis=y_data,
                    symbol="circle",
                    itemstyle_opts=opts.ItemStyleOpts(border_color='#fff'),
                    markpoint_opts=opts.MarkPointOpts(
                        label_opts=opts.LabelOpts(color='#fff'),
                        data=[
                            opts.MarkPointItem(type_='max', name='最大值'),
                            opts.MarkPointItem(type_='min', name='最小值'),
                            opts.MarkLineItem(type_="average", name="平均值")
                        ]),
                    markline_opts=opts.MarkLineItem(type_='average'),
                    is_symbol_show=True,
                    label_opts=opts.LabelOpts(is_show=False),
                    is_connect_nones=True))
        line.render(line_path)

    chart = open(line_path).read()
    return HttpResponse(chart)
Exemple #7
0
    def echarts(self):
        self._align_data()
        c = charts.Line()

        for k, v in self.curve_values.items():
            c.add_xaxis([str(i) for i in self.x_axis])
            break
        for k, v in self.curve_values.items():
            c.add_yaxis(
                v[self.name_key],
                v[self.y_key],
                label_opts=opts.LabelOpts(is_show=False),
                is_symbol_show=False,
            )

        c.set_global_opts(
            title_opts=opts.TitleOpts(title=self.title),
            tooltip_opts=opts.TooltipOpts(is_show=True, trigger='axis'),
        )

        return c
Exemple #8
0
#增加一个数据系列
y1 = [1200,500,200]
bar.add_yaxis(series_name = '公司B',yaxis_data=y1) 
bar.render(r'D:\Python Spyder\数据可视化\My PyEcharts\柱状图3.html')

# 变成条形图
bar.reversal_axis()
bar.render(r'D:\Python Spyder\数据可视化\My PyEcharts\条形图.html')

#========================================================================

# 折线图
x1 = ['2017','2018','2019']
y1 = [300,900,500]
line = pyec.Line()
line.add_xaxis(x1)
line.add_yaxis(series_name='A',y_axis = y1)
line.render(r'D:\Python Spyder\数据可视化\My PyEcharts\折线图.html')

# Line 增加提示项目
#提示项 Tool

line.set_global_opts(title_opts=opts.TitleOpts(title = '我的pyecharts'),
                     tooltip_opts = opts.TooltipOpts(trigger='axis',axis_pointer_type='cross'),
                     # 工具箱设置  is_show = True 默认展示图例     
                     #orient 参数 :horizontal 横向  v  纵向
                     toolbox_opts = opts.ToolboxOpts(is_show=True,orient='horizontal'),
                     # 设置滚动条
                     datazoom_opts=opts.DataZoomOpts(type_='slider',range_start=(),range_end=2500)
                     )
Exemple #9
0
def drawtable_detail(request):
    #  time.sleep(0.1)  # 测试前端用户感知
    json_data = request.body.decode('utf-8')
    info = json.loads(json_data)
    table_name = info.get('table_name', '').strip()
    JSFUNC = """<span style='color:yellow;font-size:20px'>节点<span>
     <span style='color:red;font-size:30px'>{line}<br>------<span>"""  # { 图表的名字 line } 或者{ @[index] }
    # line_path = 'mycharts/render/tabledata/charts_%s.html' % table_name.split('.')[1]
    # 部署到apache服务器后需要使用绝对路径
    line_path = os.path.join(
        app_dir, 'render/tabledata/charts_%s.html' % table_name.split('.')[1])
    print("line_path %s" % line_path)
    if not os.path.exists(
            line_path) or time.time() - os.path.getmtime(line_path) > 60:
        table = get_object_or_404(TableData, table_name=table_name)
        line_name = table.table_name
        table_data = table.table_data
        x_data = table_data.get("total_diff_rate").keys()
        y_data = table_data.get("total_diff_rate").values()
        column_diff_rate = table_data.get("column_diff_rate")

        line = (
            charts.Line(init_opts=opts.InitOpts(
                theme=ThemeType.SHINE)).set_series_opts(
                    label_opts=opts.LabelOpts(formatter=JSFUNC,
                                              position='right')).
            set_global_opts(
                # toolbox_opts=opts.ToolboxOpts(is_show=True, feature=opts.ToolBoxFeatureOpts(
                #     save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(is_show=True))),
                tooltip_opts=opts.TooltipOpts(is_show=True),
                xaxis_opts=opts.AxisOpts(type_="category"),
                yaxis_opts=opts.AxisOpts(
                    type_="value",
                    axistick_opts=opts.AxisTickOpts(is_show=True),
                    splitline_opts=opts.SplitLineOpts(is_show=True),
                ),
                title_opts=opts.TitleOpts(
                    title="差异比",
                    subtitle="单位1")).add_xaxis(xaxis_data=x_data).add_yaxis(
                        series_name=line_name,
                        y_axis=y_data,
                        symbol="circle",
                        itemstyle_opts=opts.ItemStyleOpts(border_color='#fff'),
                        markpoint_opts=opts.MarkPointOpts(
                            label_opts=opts.LabelOpts(color='red'),
                            data=[
                                opts.MarkPointItem(type_='max', name='最大值'),
                                opts.MarkPointItem(type_='min', name='最小值'),
                                opts.MarkLineItem(type_="average", name="平均值")
                            ]),
                        markline_opts=opts.MarkLineItem(type_='average'),
                        is_symbol_show=True,
                        label_opts=opts.LabelOpts(is_show=False),
                        is_connect_nones=True))
        for column, diff_data in column_diff_rate.items():
            tmp = []
            for day in x_data:
                tmp.append(diff_data.get(day, None))
            line.add_yaxis(
                series_name=column,
                y_axis=tmp,
                symbol="circle",
                # itemstyle_opts=opts.ItemStyleOpts(border_color='#fff'),
                # markpoint_opts=opts.MarkPointOpts(
                #     label_opts=opts.LabelOpts(color='#fff'),
                #     data=[opts.MarkPointItem(type_='max', name='最大值'), opts.MarkPointItem(type_='min', name='最小值'),
                #           opts.MarkLineItem(type_="average", name="平均值")]
                #
                # ),
                markline_opts=opts.MarkLineItem(type_='average'),
                is_symbol_show=True,
                label_opts=opts.LabelOpts(is_show=False),
                is_connect_nones=True)

        line.render(line_path)

    chart = open(line_path).read()
    return HttpResponse(chart)
line = pyc.Line(init_opts=opts.InitOpts(
    theme=glbs.ThemeType.DARK, width='100%')).add_xaxis(list(
        data.iloc[:, 0])).add_yaxis('Beijing AQI', list(
            data.iloc[:, 1])).set_series_opts(
                label_opts=opts.LabelOpts(is_show=False),
                markline_opts=opts.MarkLineOpts(
                    label_opts=opts.LabelOpts(position='end'),
                    linestyle_opts=opts.LineStyleOpts(color='#333'),
                    data=[{
                        'yAxis': y
                    } for y in [50, 100, 150, 200, 300]])).set_global_opts(
                        title_opts=opts.TitleOpts(title='Beijing AQI',
                                                  pos_left='1%'),
                        legend_opts=opts.LegendOpts(is_show=False),
                        visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                          pos_top=50,
                                                          pos_right=10,
                                                          pieces=[{
                                                              'min':
                                                              0,
                                                              'max':
                                                              50,
                                                              'color':
                                                              '#93CE07'
                                                          }, {
                                                              'min':
                                                              50,
                                                              'max':
                                                              100,
                                                              'color':
                                                              '#FBDB0F'
                                                          }, {
                                                              'min':
                                                              100,
                                                              'max':
                                                              150,
                                                              'color':
                                                              '#FC7D02'
                                                          }, {
                                                              'min':
                                                              150,
                                                              'max':
                                                              200,
                                                              'color':
                                                              '#FD0100'
                                                          }, {
                                                              'min':
                                                              200,
                                                              'max':
                                                              300,
                                                              'color':
                                                              '#AA069F'
                                                          }, {
                                                              'min':
                                                              300,
                                                              'color':
                                                              '#AC3B2A'
                                                          }]),
                        datazoom_opts=[
                            opts.DataZoomOpts(start_value='2014-06-01',
                                              range_start=None,
                                              range_end=None),
                            opts.DataZoomOpts(type_='inside')
                        ],
                        tooltip_opts=opts.TooltipOpts(trigger='axis'),
                        toolbox_opts=opts.ToolboxOpts(pos_left=None,
                                                      pos_right=10,
                                                      feature={
                                                          'dataZoom': {},
                                                          'restore': {},
                                                          'saveAsImage': {}
                                                      }),
                        yaxis_opts=opts.AxisOpts(
                            splitline_opts=opts.SplitLineOpts(is_show=True)))
Exemple #11
0
line = (c.Line().add_xaxis(x_data).add_yaxis(
    'pv', pv, label_opts=opts.LabelOpts(is_show=False)).add_yaxis(
        'uv',
        yaxis_index=1,
        y_axis=uv,
        label_opts=opts.LabelOpts(is_show=False)).extend_axis(
            yaxis=opts.AxisOpts(name='uv',
                                type_='value',
                                min_=0,
                                max_=1.6,
                                interval=.4,
                                axislabel_opts=opts.LabelOpts(
                                    formatter='{value}万人'))).
        set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=True,
                                          trigger="axis",
                                          axis_pointer_type="cross"),
            xaxis_opts=opts.AxisOpts(
                type_="category",
                axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                      type_="shadow"),
            ),
            yaxis_opts=opts.AxisOpts(
                name="pv",
                type_="value",
                min_=0,
                max_=100,
                interval=20,
                axislabel_opts=opts.LabelOpts(formatter="{value} 万次"),
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            title_opts=opts.TitleOpts(title="pv与uv趋势图"),
        ))