Ejemplo n.º 1
0
def save_map():
    chart = Highchart()

    chart.set_options('chart', {'inverted': True})

    options = {
        'title': {
            'text': 'LoadBoy 接口负载图'
        },
        'subtitle': {
            'text': '响应时间/吞吐量/线程数'
        },
        'xAxis': {
            'reversed': False,
            'title': {
                'enabled': True,
                'text': '响应时间'
            },
            'labels': {
                'formatter':
                'function () {\
                    return this.value + " t/s";\
                }'
            },
            'maxPadding': 0.05,
            'showLastLabel': True
        },
        'yAxis': {
            'title': {
                'text': '线程数'
            },
            'labels': {
                'formatter':
                "function () {\
                    return this.value + '';\
                }"
            },
            'lineWidth': 2
        },
        'legend': {
            'enabled': False
        },
        'tooltip': {
            'headerFormat': '<b>{series.name}</b><br/>',
            'pointFormat': ''
        }
    }

    chart.set_dict_options(options)

    global rt2
    global tps
    global t_num
    tps_data = list(zip(tps, t_num))
    chart.add_data_set(tps_data, 'spline', 'tps', marker={'enabled': False})

    rt_data = list(zip(rt2, t_num))
    chart.add_data_set(rt_data, 'line', 'rt', marker={'enabled': False})

    chart.save_file()
Ejemplo n.º 2
0
def renderChart(stats, bottom, left="Workflow Job"):
    keys = [k for k, _ in stats.items()]
    values = [v for _, v in stats.items()]

    chart = Highchart()

    chart.set_options("chart", {"inverted": True})

    options = {
        "title": {
            "text": "{0} by {1}".format(bottom, left)
        },
        "xAxis": {
            "categories": keys,
            "title": {
                "text": left
            },
            "maxPadding": 0.05,
            "showLastLabel": True,
        },
        "yAxis": {
            "title": {
                "text": bottom
            },
            "labels": {
                "formatter":
                "function () {\
                    return this.value;\
                }"
            },
            "lineWidth": 2,
        },
        "legend": {
            "enabled": False
        },
        "tooltip": {
            "headerFormat": "<b>{series.name}</b><br/>",
            "pointFormat": "{point.x} : {point.y}",
        },
    }

    chart.set_dict_options(options)
    chart.add_data_set(values, "bar")

    return str(chart)
Ejemplo n.º 3
0
def hc_basic_line(data, title, subtitle=None, y_axis=None, labels=None, theme=None):
    H = Highchart()

    H.set_options("title", {
        "text": title
    })

    if subtitle:
        H.set_options("subtitle", {
            "text": subtitle
        })

    if y_axis:
        H.set_options("yAxis", {
            "title": {
                "text": y_axis
            }
        })

    H.set_options("legend", {
        "layout": "vertical",
        "align": "right",
        "verticalAlign": "middle"
    })

    # transform the data from a list of rows to a list of columns
    data_t = list(zip(*data))

    # Use the first column as the X axis
    x_axis = data_t[0]

    H.set_options("xAxis", {
        "categories": x_axis,
        "tickmarkPlacement": "on"
    })

    # And the remaining columns as the graph data
    if not labels:
        labels = ["series_%d" % i for i in range(len(data_t)-1)]

    for label, series in zip(labels, data_t[1:]):
        H.add_data_set(series, series_type='line', name=label)

    return hc_plot(H, title, theme)
Ejemplo n.º 4
0
def stat():
    '''
    Pagina con le statistiche nel periodo selezionato
    '''
    # input GET
    if request.method == 'GET':
        start_date = request.args.get('start_date', '')
        stop_date = request.args.get('stop_date', '')

    # calcolo consumo
    dati = calcoloConsumo()
    auto_selezionata = 'Fiesta'
    ind = (dati['data'] >= datetime.datetime.strptime(start_date,'%Y-%m-%d')) & \
            (dati['data'] <= datetime.datetime.strptime(stop_date,'%Y-%m-%d')) & \
            (dati['auto'] == auto_selezionata)
    dati_filt = dati.loc[ind, :].drop(
        ['id', 'insertdate', 'chilometri_last', 'chilometri_delta'],
        axis=1).reset_index(drop=True).copy()

    # Grafico
    chart = Highchart(width=600, height=500)
    chart.add_data_set(dati_filt[['data', 'euro al litro']].values.tolist(),
                       series_type='line',
                       name='Prezzo (€/litro)')
    chart.add_data_set(dati_filt[['data',
                                  'chilometri con un litro']].values.tolist(),
                       series_type='line',
                       name='km con un litro')
    chart.add_data_set(dati_filt[['data', 'chilometri con un litro CUM'
                                  ]].values.tolist(),
                       series_type='line',
                       name='km con un litro avg')

    chart.set_options('xAxis', {'type': 'datetime', 'gridLineWidth': 1})
    #    chart.set_options('chart', {'backgroundColor':'transparent'})
    chart.set_options('tooltip', {'formatter': 'default_tooltip'})
    chart.set_options('title', {'text': 'Statistiche consumo'})
    chart.htmlcontent

    return render_template(
        'gas_stat.html',
        start_date=start_date,
        stop_date=stop_date,
        df1=dati_filt.to_html(classes='table', index=False,
                              escape=True).replace(
                                  '<th>',
                                  '<th style = "background-color: #000099"	>'),
        fig1_head=chart.htmlheader,
        fig1_body=chart.content)
Ejemplo n.º 5
0
def piscinaStat():
    '''
    Pagina con le statistiche degli allenamenti nel periodo selezionato
    '''
    # input GET
    if request.method == 'GET':
        start_date = request.args.get('start_date', '')
        stop_date = request.args.get('stop_date', '')
    
    # Scarico i dati da DB: allenamenti compresi tra le date specificate
    query_text = ("""SELECT strftime('%Y',data) AS anno
                 , strftime('%m',data) AS mese
                 , count(0) AS Nvolte
                 , sum(n_vasche * 25 / lung_vasche) AS somma_vasche
                 , round(avg(n_vasche * 25 / lung_vasche), 1) AS media_vasche
                 , sum(n_vasche * lung_vasche) AS somma_metri
                 , round(avg(n_vasche * lung_vasche), 0) AS media_metri
            FROM piscina_allenamenti
            JOIN nome_piscina
                ON piscina_allenamenti.id_nome_piscina = nome_piscina.id
            WHERE data >= date('"""+start_date+"""')
                AND data < date('"""+stop_date+"""')
            GROUP BY
              anno
            , mese""")
    dati = pd.read_sql_query(query_text, engine)
    dati['media_metri'] = dati['media_metri'].astype('int')
    
    # Grafico
    chart = Highchart(width = 600, height = 500)
    dff=[]
    for i in range(len(dati)):
        dff.append(str(dati.anno[i])+'/'+str(dati.mese[i]))
    chart.set_options('xAxis', {'categories': dff, 'gridLineWidth': 1})
    chart.set_options('tooltip', {'formatter': 'default_tooltip'})
    chart.set_options('title', {'text': 'Statistiche mensili allenamenti'})
#    chart.set_options('chart', {'backgroundColor':'transparent'})
    chart.add_data_set(dati.Nvolte.values.tolist(), series_type='bar', name='Numero allenamenti')
    chart.add_data_set(dati.media_metri.values.tolist(), series_type='line', name='Media metri')
    chart.add_data_set(dati.somma_metri.values.tolist(), series_type='bar', name='Somma metri')
    chart.htmlcontent;
    
    return render_template('piscina_stat.html', start_date=start_date, stop_date=stop_date, 
                           df1=dati.to_html(classes='table',index=False,escape=True).replace('<th>','<th style = "background-color: #000099"	>'), 
                               fig1_head=chart.htmlheader, fig1_body=chart.content)
Ejemplo n.º 6
0
def fuel_stat(request, auto_id=None, start_date=None, end_date=None):
    '''Stat for supply'''
    common = {"name": "Fuel"}

    # Initial-default values
    last_auto = models.Supply.objects.latest('id').auto
    start_date_init = timezone.now().date() + timezone.timedelta(days=-60)
    end_date_init = timezone.now().date()

    # get form
    form = forms.FuelStatForm(request.GET)
    if form.is_valid():
        common["auto"] = form.cleaned_data['auto']
        common["start_date"] = form.cleaned_data['start_date']
        common["end_date"] = form.cleaned_data['end_date']
    else:
        form = forms.FuelStatForm(initial={"auto":last_auto, "start_date":start_date_init,
                                "end_date":end_date_init})
        common["auto"] = last_auto
        common["start_date"] = start_date_init
        common["end_date"] = end_date_init 
    
    # Get data
    Supply = models.Supply.objects.filter(auto=common["auto"]).filter(event_date__gte=common["start_date"]) \
                        .filter(event_date__lte=common["end_date"]).order_by('event_date').all()
    cum_sum = [[0, 0, 0]] # calcolo la somma, per ottenere la cumulata  
    for supply in Supply:
        supply.calcStat()
        cum_sum.append([supply.event_date, cum_sum[-1][1]+supply.distance, cum_sum[-1][2]+supply.volume])
    cum_sum.pop(0)
    
    # Highchart
    chart = Highchart(height = 500)
    chart.add_data_set([[1000*(a.event_date-datetime.date(1970,1,1)).total_seconds(), int(a.pricevolume*100)/100] for a in Supply], series_type='line', name='Prezzo (€/litro)')
    chart.add_data_set([[1000*(a.event_date-datetime.date(1970,1,1)).total_seconds(), int(a.consumption1*100)/100] for a in Supply], series_type='line', name='km con un litro')
    chart.add_data_set([[1000*(a[0]-datetime.date(1970,1,1)).total_seconds(), int(a[1]/a[2]*100)/100] for a in cum_sum], series_type='line', name='km con un litro (tendenza)')
    
    chart.set_options('xAxis', {'type': 'datetime', 'gridLineWidth': 1})
#    chart.set_options('chart', {'backgroundColor':'transparent'})
    chart.set_options('tooltip', {'formatter': 'default_tooltip'})
    chart.set_options('title', {'text': f"Statistiche consumo {common['auto']}"})
    chart.htmlcontent;
    chart_dict = {"header": chart.htmlheader, "content":chart.content}

    return render(request, 'alldoc/fuel_stat.html', {"common": common, "Supply": Supply, "form": form, "chart": chart_dict})
# -*- coding: utf-8 -*-
"""
Highcharts Demos
Spline with inverted axes: http://www.highcharts.com/demo/spline-inverted
"""
from highcharts import Highchart
H = Highchart()

# set option
H.set_options('chart', {'inverted': True})

# highchart option can be also set as a dict object
# first construct the dict object for all the options:
options = {
    'title': {
        'text': 'Atmosphere Temperature by Altitude'
    },
    'subtitle': {
        'text': 'According to the Standard Atmosphere Model'
    },
    'xAxis': {
        'reversed': False,
        'title': {
            'enabled': True,
            'text': 'Altitude'
        },
        'labels': {
            'formatter':
            'function () {\
                                return this.value + "km";\
                            }'
Ejemplo n.º 8
0
def draw(folderName, videoName, modelName):
    # videoName = '6'#define your test video name here
    fileList = getJsonList(folderName)
    fileList = set(fileList)
    print(len(fileList))
    fullData = []
    initFrame = 0
    while (folderName + "_" + str(initFrame + 29).zfill(12) + "_keypoints.json"
           in fileList):
        matrix = []
        for i in range(30):
            file = folderName + "_" + str(initFrame +
                                          i).zfill(12) + "_keypoints.json"
            matrixLine = getJsonForOneFrame(folderName + '/' + file,
                                            folderName)

            matrix.append(matrixLine)
        fullData.append(matrix)
        initFrame += 30

    def cleanX(raw):
        length = len(raw)
        temp = np.zeros((length, 10, 190))
        for i in range(len(raw)):
            for j in range(10):
                for k in range(190):
                    temp[i][j][k] = raw[i][j][k]
            print("progress:{0}%".format(round((i + 1) * 100 / len(raw))),
                  end="\r")
        return temp

    temp = cleanX(fullData)

    #     model1 = load_model('10/balancetalking.h5')
    #     r1 = model1.predict(temp)

    #     model2 = load_model('10/balancedrinking.h5')
    #     r2 = model2.predict(temp)

    def ProcessSilentData(x_train, x_test):
        def proc(x_train_silent):
            length = len(x_train_silent)
            temp = np.zeros((length, 10, 46))
            for i in range(len(x_train_silent)):
                for j in range(10):
                    for k in range(190):
                        if 146 <= k <= 185:
                            temp[i][j][k - 146] = x_train_silent[i][j][k]
                    temp[i][j][40] = x_train_silent[i][j][67]  # face
                    temp[i][j][41] = x_train_silent[i][j][68]
                    temp[i][j][42] = x_train_silent[i][j][8]  # left hand
                    temp[i][j][43] = x_train_silent[i][j][9]
                    temp[i][j][44] = x_train_silent[i][j][14]  # right hand
                    temp[i][j][45] = x_train_silent[i][j][15]

            return temp

        x_train_40 = proc(x_train)
        x_test_40 = proc(x_test)
        x_train = x_train_40
        x_test = x_test_40

        # define distance between two points
        def calDis(material, a, b):
            # material = x_train[0][0]
            ax = (a - 1) * 2
            ay = ax + 1
            bx = (b - 1) * 2
            by = bx + 1
            d1 = abs(material[ax] - material[bx])
            d2 = abs(material[ay] - material[by])
            dis = np.sqrt(d1 * d1 + d2 * d2)
            return dis

        def getSilent(x):  # x_train[0][0]
            mouthLen = calDis(x, 13, 17)
            sideLen = calDis(x, 1, 12) + calDis(x, 1, 2) + calDis(
                x, 8, 7) + calDis(x, 6, 7)
            mouthWid = calDis(x, 14, 20) + calDis(x, 15, 19) + calDis(
                x, 16, 18)
            handLen = calDis(x, 21, 22) + calDis(x, 21, 23)
            if mouthLen == 0:
                silentWeight = 0
            else:
                silentWeight = mouthWid / mouthLen
            if sideLen == 0:
                sideWeight = 0
                handWeight = 0
            else:
                sideWeight = mouthWid / sideLen
                handWeight = handLen / sideLen
            if sideLen == 0:
                return [-1, -1]
            else:
                return [sideWeight, silentWeight]

        def proX(x_train):
            pro_x_train = np.zeros((len(x_train), 10, 4))
            for i in range(len(x_train)):
                for j in range(len(x_train[i])):
                    var0, var1 = getSilent(x_train[i][j])
                    pro_x_train[i][j][0] = var0
                    pro_x_train[i][j][1] = var1
            for i in range(len(pro_x_train)):  # 10 2
                varList1 = []
                varList2 = []
                for j in range(10):
                    varList1.append(pro_x_train[i][j][0])
                    varList2.append(pro_x_train[i][j][1])
                var2 = np.var(varList1)
                var3 = np.var(varList2)
                for j in range(10):
                    pro_x_train[i][j][2] = var2
                    pro_x_train[i][j][3] = var3
            return pro_x_train

        return proX(x_train), proX(x_test)

    # print(x_train.shape)

    x_train_silent, x_test = ProcessSilentData(temp, temp)
    x_train_eat, x_test = ProcessSilentData(temp, temp)

    model4 = load_model('talking.h5')  # 还是两个点的silenttalking不要动摇
    r4 = model4.predict(x_train_silent)

    model3 = load_model('confusing.h5')  # eating不要只搞两个点
    r3 = model3.predict(x_train_eat)

    # print(r4)

    X_TRAIN = []
    for i in range(len(r4)):
        # X_TRAIN.append([[r1[i][0]], [r2[i][0]], [r3[i][0]], [r4[i][0]]])
        X_TRAIN.append([[r4[i][0]], [r3[i][0]]])
    X_TRAIN = np.array(X_TRAIN)
    # print(X_TRAIN.shape)

    model = load_model(modelName)
    predict = model.predict(X_TRAIN)
    # return predict###########################

    a = predict.tolist()
    result = []
    frames = 30
    for i in a:
        result.append([frames, i[0]])
        frames += 30
    # print(result)
    chart = Highchart()
    chart.set_options('chart', {'inverted': False})
    options = {
        'title': {
            'text': 'Prediction for video ' + folderName + '.mp4'
        },
        'subtitle': {
            'text': '1 means talking while 0 means non-talking'
        },
        'xAxis': {
            'title': {
                'text': 'Second'
            }
        },
        'yAxis': {
            'title': {
                'text': 'Flag'
            },
        }
    }
    chart.set_dict_options(options)
    chart.add_data_set(result, series_type='line', name='prediction')
    newresult = []
    for r in result:
        newresult.append([r[0] / 30, 0.5])
    chart.add_data_set(newresult, series_type='line', name='talking/silent')

    index = []
    for i in result:
        for j in range(30):
            index.append(i[1])

    import cv2
    video = videoName
    result_video = folderName + '_result.mp4'
    cap = cv2.VideoCapture(video)
    fps_video = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    videoWriter = cv2.VideoWriter(result_video, fourcc, fps_video,
                                  (frame_width, frame_height))
    frame_id = 0
    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            frame_id += 1
            left_x_up = int(frame_width / frame_id)
            left_y_up = int(frame_height / frame_id)
            right_x_down = int(left_x_up + frame_width / 10)
            right_y_down = int(left_y_up + frame_height / 10)
            word_x = left_x_up + 5
            word_y = left_y_up + 25
            if frame_id >= len(index):
                pass
            else:
                cv2.putText(frame, 'frame_%s' % index[frame_id],
                            (word_x, word_y), cv2.FONT_HERSHEY_SIMPLEX, 1,
                            (55, 255, 155), 2)
            videoWriter.write(frame)
        else:
            videoWriter.release()
            break

    frameRate = 30  # default video frame rate
    for i in result:
        i[0] = i[0] / frameRate

    d = {}
    d['talking'] = result
    file_name = 'timeLabel.json'
    with open(file_name, 'w') as file_object:
        json.dump(d, file_object)

    file_name = '430000313.json'
    with open(file_name, 'w') as file_object:
        json.dump(d, file_object)

    return chart
# -*- coding: utf-8 -*-
"""
Highcharts Demos
Spline with inverted axes: http://www.highcharts.com/demo/spline-inverted
"""
from highcharts import Highchart
H = Highchart()

# set option 
H.set_options('chart', {'inverted': True})

# highchart option can be also set as a dict object
# first construct the dict object for all the options:
options = {
    'title': {
        'text': 'Atmosphere Temperature by Altitude'
    },
    'subtitle': {
        'text': 'According to the Standard Atmosphere Model'
    },
    'xAxis': {
        'reversed': False,
        'title': {
            'enabled': True,
            'text': 'Altitude'
        },
        'labels': {
            'formatter': 'function () {\
                                return this.value + "km";\
                            }'
        },
Ejemplo n.º 10
0
def drawColumnChart(emotions):
	H_column = Highchart(width=750, height=600)
	H_column.set_options('xAxis',{'categories':['Before','After']})
	drawChart(options_column,H_column,'column',emotions,'output_charts_column')
Ejemplo n.º 11
0
'''
Add them to Violin series
'''
chart = Violin(center='mean')
chart.addSeries(dataset_1, name=dataset_names[0])
chart.addSeries(dataset_2, name=dataset_names[1])
chart.addSeries(dataset_3, name=dataset_names[2])
'''
Plot horizontal chart to file <horizontal.html>
'''
hc = Highchart()
hc.set_options(
    'yAxis', {
        'categories': dataset_names,
        'min': 0,
        'max': len(dataset_names) - 1,
        'title': {
            'text': ''
        },
        'gridLineWidth': 0
    })
hc.set_options('title', {'text': 'example'})
for s in chart.series_list():
    s['supress_errors'] = True  # otherwise setting attr 'linkTo' raise error
    hc.add_data_set(**s)
hc.save_file(filename='example_horizontal')
'''
Plot vertical chart to file <vertical.html>
'''
hc = Highchart()
hc.set_options('chart', {'inverted': True})
hc.set_options('xAxis', {'reversed': False})
Ejemplo n.º 12
0
            plot = []
            if data is None:
                print("Sorry, No Results Are Found!")
            else:
                table = PrettyTable()
                table.field_names = ["Hashtag", "Count"]
                for row in data:
                    hashtag = row[1]
                    count = row[0]
                    table.add_row([hashtag, count])
                    plot.append([hashtag, count])
                print(table)

            chart = Highchart(width=664, height=400)

            chart.set_options('chart', {'inverted': False})

            options = {
                'chart': {
                    'type': 'pie',
                    'options3d': {
                        'enabled': True,
                        'alpha': 45
                    }
                },
                'title': {
                    'text': 'Top Hashtags'
                },
                'subtitle': {
                    'text': 'Observed in Kansas City, Kansas, USA'
                },
Ejemplo n.º 13
0
def plot_scatter(molmap, htmlpath='./', htmlname=None, radius=3):
    '''
    molmap: the object of molmap
    htmlpath: the figure path, not include the prefix of 'html'
    htmlname: the name 
    radius: int, defaut:3, the radius of scatter dot
    '''

    title = '2D emmbedding of %s based on %s method' % (molmap.ftype,
                                                        molmap.method)
    subtitle = 'number of %s: %s, metric method: %s' % (
        molmap.ftype, len(molmap.flist), molmap.metric)
    name = '%s_%s_%s_%s_%s' % (molmap.ftype, len(
        molmap.flist), molmap.metric, molmap.method, 'scatter')

    if not os.path.exists(htmlpath):
        os.makedirs(htmlpath)

    if htmlname:
        name = htmlname + '_' + name

    filename = os.path.join(htmlpath, name)
    print_info('generate file: %s' % filename)

    xy = molmap.embedded.embedding_
    colormaps = molmap.extract.colormaps

    df = pd.DataFrame(xy, columns=['x', 'y'])
    bitsinfo = molmap.extract.bitsinfo.set_index('IDs')
    df = df.join(bitsinfo.loc[molmap.flist].reset_index())
    df['colors'] = df['Subtypes'].map(colormaps)

    H = Highchart(width=1000, height=850)
    H.set_options('chart', {'type': 'scatter', 'zoomType': 'xy'})
    H.set_options('title', {'text': title})
    H.set_options('subtitle', {'text': subtitle})
    H.set_options(
        'xAxis', {
            'title': {
                'enabled': True,
                'text': 'X',
                'style': {
                    'fontSize': 20
                }
            },
            'labels': {
                'style': {
                    'fontSize': 20
                }
            },
            'gridLineWidth': 1,
            'startOnTick': True,
            'endOnTick': True,
            'showLastLabel': True
        })

    H.set_options(
        'yAxis', {
            'title': {
                'text': 'Y',
                'style': {
                    'fontSize': 20
                }
            },
            'labels': {
                'style': {
                    'fontSize': 20
                }
            },
            'gridLineWidth': 1,
        })

    #     H.set_options('legend', {'layout': 'horizontal','verticalAlign': 'top','align':'right','floating': False,
    #                              'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'",
    #                              'borderWidth': 1})

    H.set_options(
        'legend', {
            'align': 'right',
            'layout': 'vertical',
            'margin': 1,
            'verticalAlign': 'top',
            'y': 40,
            'symbolHeight': 12,
            'floating': False,
        })

    H.set_options(
        'plotOptions', {
            'scatter': {
                'marker': {
                    'radius': radius,
                    'states': {
                        'hover': {
                            'enabled': True,
                            'lineColor': 'rgb(100,100,100)'
                        }
                    }
                },
                'states': {
                    'hover': {
                        'marker': {
                            'enabled': False
                        }
                    }
                },
                'tooltip': {
                    'headerFormat': '<b>{series.name}</b><br>',
                    'pointFormat': '{point.IDs}'
                }
            },
            'series': {
                'turboThreshold': 5000
            }
        })

    for subtype, color in colormaps.items():
        dfi = df[df['Subtypes'] == subtype]
        if len(dfi) == 0:
            continue

        data = dfi.to_dict('records')
        H.add_data_set(data, 'scatter', subtype, color=color)
    H.save_file(filename)
    print_info('save html file to %s' % filename)
    return df, H
                      2.39], [datetime(1971, 5, 20), 2.3],
                     [datetime(1971, 6, 5), 2], [datetime(1971, 6, 10), 1.85],
                     [datetime(1971, 6, 15), 1.49],
                     [datetime(1971, 6, 23), 1.08]]

H.add_data_set(winter_12_13_data,
               series_type="spline",
               name="Winter 2012-2013")
H.add_data_set(winter_13_14_data,
               series_type="spline",
               name="Winter 2013-2014")
H.add_data_set(winter_14_15_data,
               series_type="spline",
               name="Winter 2014-2015")

H.set_options('chart', {'type': 'spline'})

H.set_options(
    'xAxis',
    {
        'type': 'datetime',
        'dateTimeLabelFormats': {  # don't display the dummy year
            'month': '%e. %b',
            'year': '%b'
        },
        'title': {
            'text': 'Date'
        }
    })

H.set_options('yAxis', {'title': {'text': 'Snow depth (m)'}, 'min': 0})
    7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6
]
data_NY = [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
data_Berlin = [
    -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0
]
data_London = [
    3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8
]

H.add_data_set(data_Tokyo, 'line', 'Tokyo')
H.add_data_set(data_NY, 'line', 'New York')
H.add_data_set(data_Berlin, 'line', 'Berlin')
H.add_data_set(data_London, 'line', 'London')

H.set_options('chart', {'zoomType': 'x'})
H.set_options(
    'xAxis', {
        'categories': [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]
    })

H.set_options(
    'yAxis', {
        'title': {
            'text': 'Temperature (°C)'
        },
        'plotLines': {
            'value': 0,
Ejemplo n.º 16
0
"""
from highcharts import Highchart

H = Highchart()

data_Tokyo = [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
data_NY = [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
data_Berlin = [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
data_London = [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]

H.add_data_set(data_Tokyo, "line", "Tokyo")
H.add_data_set(data_NY, "line", "New York")
H.add_data_set(data_Berlin, "line", "Berlin")
H.add_data_set(data_London, "line", "London")

H.set_options("chart", {"zoomType": "x"})
H.set_options(
    "xAxis", {"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}
)

H.set_options(
    "yAxis", {"title": {"text": "Temperature (°C)"}, "plotLines": {"value": 0, "width": 1, "color": "#808080"}}
)
H.set_options("tooltip", {"valueSuffix": "°C"})

H.set_options("legend", {"layout": "vertical", "align": "right", "verticalAlign": "middle", "borderWidth": 0})
H.set_options("colors", {})
H.set_options("plotOptions", {"line": {"dataLabels": {"enabled": True}}})

H.htmlcontent
    else:
      top[hashtag] = 1

  data[createdAt] = counts

top = sorted(top.items(), key=lambda x: x[1], reverse=True)
sortedItems = sorted([item for item in data.items()])

series = {}
for i in range(min(int(argv[2]), len(top))):
  hashtag = top[i][0]
  dataSet = []
  for item in sortedItems:
    if hashtag in item[1]:
      dataSet.append(item[1][hashtag])
    else:
      dataSet.append(0)
  series[hashtag] = dataSet

categories = [item[0] for item in sortedItems]

chart = Highchart()
chart.set_options(TITLE, {TEXT : "Top Trending Topics Over Time"})
chart.set_options(XAXIS, {CATEGORIES : categories})
chart.set_options(YAXIS, {TITLE : {TEXT: "Results containing Hashtag"}})

for item in series.items():
  chart.add_data_set(item[1], series_type='line', name=item[0])

chart.save_file(splitext(argv[3])[0]) 
Ejemplo n.º 18
0
def pool_stat(request, start_date=None, end_date=None):
    '''Stat for Pool'''
    common = {"name": "Pool"}

    # Initial-default values
    start_date_init = (timezone.now().date() + timezone.timedelta(days=-365)).replace(day=1)
    end_date_init = timezone.now().date()

    # get form
    form = forms.PoolStatForm(request.GET)
    if form.is_valid():
        common["start_date"] = form.cleaned_data['start_date']
        common["end_date"] = form.cleaned_data['end_date']
    else:
        form = forms.PoolStatForm(initial={"start_date":start_date_init,
                                "end_date":end_date_init})
        common["start_date"] = start_date_init
        common["end_date"] = end_date_init 
    
    # Get data
    PoolSession = models.PoolSession.objects.filter(event_date__gte=common["start_date"]) \
                        .filter(event_date__lte=common["end_date"]).order_by('event_date').all()
    diz = {} # calcolo il group by mese/anno
    list_date = []  
    for sess in PoolSession:
        sess.metri = sess.lap_number * sess.pool.lap_length
        annomese = str(sess.event_date.month).zfill(2)+"-"+str(sess.event_date.year)
        # First month appearence
        if annomese not in list_date:
            diz[annomese] = {'data': sess.event_date.replace(day=1), 
                             'allenamenti': 0, 
                             'vasche_norm': 0,
                             'metri': 0}
            list_date.append(annomese)
        # Add values
        diz[annomese]['allenamenti'] += 1
        diz[annomese]['vasche_norm'] += sess.lap_number * sess.pool.lap_length / 25 # normalize to 25m length
        diz[annomese]['metri'] += sess.lap_number * sess.pool.lap_length
    
    # Save in list
    list_stat = []
    for a in list_date:
        diz[annomese]['vasche_norm'] = int( diz[annomese]['vasche_norm'])
        diz[a]['media_vasche'] = int(diz[a]['vasche_norm']/diz[a]['allenamenti'])
        diz[a]['media_metri'] = int(diz[a]['metri']/diz[a]['allenamenti'])
        list_stat.append(diz[a])

    # Highchart ToDo: rewrite with list_stat
    chart = Highchart(height = 500)
    chart.add_data_set([[1000*(diz[a]['data']-datetime.date(1970,1,1)).total_seconds(), diz[a]['allenamenti']] for a in list_date], 
                        series_type='line', name='Allenamenti')
    chart.add_data_set([[1000*(diz[a]['data']-datetime.date(1970,1,1)).total_seconds(), diz[a]['media_vasche']] for a in list_date], 
                        series_type='bar', name='Media vasche')
    chart.add_data_set([[1000*(diz[a]['data']-datetime.date(1970,1,1)).total_seconds(), diz[a]['metri']] for a in list_date], 
                        series_type='bar', name='metri')
    
    chart.set_options('xAxis', {'type': 'datetime', 'gridLineWidth': 1})
#    chart.set_options('chart', {'backgroundColor':'transparent'})
    chart.set_options('tooltip', {'formatter': 'default_tooltip'})
    chart.set_options('title', {'text': f"Statistiche allenamenti in piscina"})
    chart.htmlcontent;
    chart_dict = {"header": chart.htmlheader, "content":chart.content}

    return render(request, 'alldoc/pool_stat.html', {"common": common, "PoolSession": PoolSession, "form": form, "chart": chart_dict, "list_stat": list_stat})
Ejemplo n.º 19
0
    },
    events={
        'click': "function (event) { alert(this.name + ' clicked\\n' + 'Alt: ' + event.altKey + '\\n' + \
                 'Control: ' + event.ctrlKey + '\\n' + 'Shift: ' + event.shiftKey + '\\n');}"}, 
    dashStyle='ShortDash'
)

"""
Set up highchart options using 
1. set_options method:  
    set_options(option_type, option_dict)
    option_type is the keyword for highchart options
    option_dict is (python) dict for option settings
    (for option details please ref to highcharts API: http://api.highcharts.com/highcharts#)
"""
H.set_options('chart', {'resetZoomButton': {'relativeTo': 'plot', 'position': {'x': 0, 'y': -30}}})
H.set_options('xAxis', {'events': {'afterBreaks': 'function(e){return}'}})
H.set_options('tooltip', {'formatter': 'default_tooltip'})
H.set_options('xAxis', {'events': {'pointBreak': 'function(e){return}'}})
H.set_options('chart', {'style': {'fontFamily': 'Lucida Grande, sans-serif', "fontfontSize": '12px'}})
H.set_options('chart', {'style': {"fontfontSize": '22px'}})
H.set_options('chart', {'resetZoomButton': {'position': {'x': 10}}})
H.set_options('chart', {'resetZoomButton': {'relativeTo': 'chart'}})

"""
Set up highchart options using 
2. set_dict_options method: 
    set_dict_options(options)
    option is a (python) dict for options settings

The way to use this method is very similar to the options object as on highcharts docs:
    [datetime(1971, 5, 5), 2.68],
    [datetime(1971, 5, 10), 2.56],
    [datetime(1971, 5, 15), 2.39],
    [datetime(1971, 5, 20), 2.3],
    [datetime(1971, 6, 5), 2],
    [datetime(1971, 6, 10), 1.85],
    [datetime(1971, 6, 15), 1.49],
    [datetime(1971, 6, 23), 1.08]
]

H.add_data_set(winter_12_13_data, series_type="spline", name="Winter 2012-2013")
H.add_data_set(winter_13_14_data, series_type="spline", name="Winter 2013-2014")
H.add_data_set(winter_14_15_data, series_type="spline", name="Winter 2014-2015")

H.set_options('chart', {
    'type': 'spline'
})

H.set_options('xAxis', {
    'type': 'datetime',
    'dateTimeLabelFormats': { # don't display the dummy year
        'month': '%e. %b',
        'year': '%b'
    },
    'title': {
        'text': 'Date'
    }
})

H.set_options('yAxis', {
    'title': {
    [8, 1, 97],
    [8, 2, 123],
    [8, 3, 64],
    [8, 4, 84],
    [9, 0, 47],
    [9, 1, 114],
    [9, 2, 31],
    [9, 3, 48],
    [9, 4, 91]
]

H.add_data_set(data, )

H.set_options('chart', {
    'type': 'heatmap',
    'marginTop': 40,
    'marginBottom': 80,
    'plotBorderWidth': 1
})

H.set_options('xAxis', {
    'categories': 
        ['Alexander', 'Marie', 'Maximilian', 'Sophia', 'Lukas', 'Maria', 'Leon', 'Anna', 'Tim', 'Laura']
})

H.set_options('yAxis', {
    'categories': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
    'title': None
})

H.set_options('title', {
    'text': "Sales per employee per weekday"
# -*- coding: utf-8 -*-
"""
Highcharts Demos
Time series, zoomable: http://www.highcharts.com/demo/line-time-series
"""

import datetime
from highcharts import Highchart

H = Highchart()

H.set_options('chart', {'zoomType': 'x'})
H.set_options('xAxis', {'type': 'datetime',
            'minRange': 14 * 24 * 3600000})

H.set_options('yAxis',{ 'title': { 'text': 'Exchange rate'}})
H.set_options('title', {'text': 'USD to EUR exchange rate from 2006 through 2008'})
H.set_options('legend', {'enabled': False})



data =  [ # copy dataset from http://www.highcharts.com/samples/data/jsonp.php?filename=usdeur.json&callback=?
    0.8446, 0.8445, 0.8444, 0.8451,    0.8418, 0.8264,    0.8258, 0.8232,    0.8233, 0.8258,
    0.8283, 0.8278, 0.8256, 0.8292,    0.8239, 0.8239,    0.8245, 0.8265,    0.8261, 0.8269,
    0.8273, 0.8244, 0.8244, 0.8172,    0.8139, 0.8146,    0.8164, 0.82,    0.8269, 0.8269,
    0.8269, 0.8258, 0.8247, 0.8286,    0.8289, 0.8316,    0.832, 0.8333,    0.8352, 0.8357,
    0.8355, 0.8354, 0.8403, 0.8403,    0.8406, 0.8403,    0.8396, 0.8418,    0.8409, 0.8384,
    0.8386, 0.8372, 0.839, 0.84, 0.8389, 0.84, 0.8423, 0.8423, 0.8435, 0.8422,
    0.838, 0.8373, 0.8316, 0.8303,    0.8303, 0.8302,    0.8369, 0.84, 0.8385, 0.84,
    0.8401, 0.8402, 0.8381, 0.8351,    0.8314, 0.8273,    0.8213, 0.8207,    0.8207, 0.8215,
    0.8242, 0.8273, 0.8301, 0.8346,    0.8312, 0.8312,    0.8312, 0.8306,    0.8327, 0.8282,
Ejemplo n.º 23
0
def plot_grid(molmap, htmlpath='./', htmlname=None):
    '''
    molmap: the object of molmap
    htmlpath: the figure path
    '''

    if not os.path.exists(htmlpath):
        os.makedirs(htmlpath)

    title = 'Assignment of %s by %s emmbedding result' % (molmap.ftype,
                                                          molmap.method)
    subtitle = 'number of %s: %s, metric method: %s' % (
        molmap.ftype, len(molmap.flist), molmap.metric)

    name = '%s_%s_%s_%s_%s' % (molmap.ftype, len(
        molmap.flist), molmap.metric, molmap.method, 'molmap')

    if htmlname:
        name = name = htmlname + '_' + name

    filename = os.path.join(htmlpath, name)
    print_info('generate file: %s' % filename)

    m, n = molmap.fmap_shape
    colormaps = molmap.extract.colormaps
    position = np.zeros(molmap.fmap_shape, dtype='O').reshape(m * n, )
    position[molmap._S.col_asses] = molmap.flist
    position = position.reshape(m, n)

    x = []
    for i in range(n):
        x.extend([i] * m)

    y = list(range(m)) * n

    v = position.reshape(m * n, order='f')

    df = pd.DataFrame(list(zip(x, y, v)), columns=['x', 'y', 'v'])
    bitsinfo = molmap.extract.bitsinfo
    subtypedict = bitsinfo.set_index('IDs')['Subtypes'].to_dict()
    subtypedict.update({0: 'NaN'})
    df['Subtypes'] = df.v.map(subtypedict)
    df['colors'] = df['Subtypes'].map(colormaps)

    H = Highchart(width=1000, height=850)
    H.set_options('chart', {'type': 'heatmap', 'zoomType': 'xy'})
    H.set_options('title', {'text': title})
    H.set_options('subtitle', {'text': subtitle})

    #     H.set_options('xAxis', {'title': '',
    #                             'min': 0, 'max': molmap.fmap_shape[1]-1,
    #                             'allowDecimals':False,
    #                             'labels':{'style':{'fontSize':20}}})

    #     H.set_options('yAxis', {'title': '', 'tickPosition': 'inside',
    #                             'min': 0, 'max': molmap.fmap_shape[0]-1,
    #                             'reversed': True,
    #                             'allowDecimals':False,
    #                             'labels':{'style':{'fontSize':20}}})

    H.set_options(
        'xAxis', {
            'title': None,
            'min': 0,
            'max': molmap.fmap_shape[1],
            'startOnTick': False,
            'endOnTick': False,
            'allowDecimals': False,
            'labels': {
                'style': {
                    'fontSize': 20
                }
            }
        })

    H.set_options(
        'yAxis', {
            'title': {
                'text': ' ',
                'style': {
                    'fontSize': 20
                }
            },
            'startOnTick': False,
            'endOnTick': False,
            'gridLineWidth': 0,
            'reversed': True,
            'min': 0,
            'max': molmap.fmap_shape[0],
            'allowDecimals': False,
            'labels': {
                'style': {
                    'fontSize': 20
                }
            }
        })

    H.set_options(
        'legend', {
            'align': 'right',
            'layout': 'vertical',
            'margin': 1,
            'verticalAlign': 'top',
            'y': 60,
            'symbolHeight': 12,
            'floating': False,
        })

    H.set_options('tooltip', {
        'headerFormat': '<b>{series.name}</b><br>',
        'pointFormat': '{point.v}'
    })

    H.set_options('plotOptions', {'series': {'turboThreshold': 5000}})

    for subtype, color in colormaps.items():
        dfi = df[df['Subtypes'] == subtype]
        if len(dfi) == 0:
            continue
        H.add_data_set(
            dfi.to_dict('records'),
            'heatmap',
            name=subtype,
            color=color,  #dataLabels = {'enabled': True, 'color': '#000000'}
        )
    H.save_file(filename)
    print_info('save html file to %s' % filename)

    return df, H
Ejemplo n.º 24
0
def drawAreaChart(emotions,chatLog):
	H_area = Highchart(width=750, height=600)
	H_area.set_options('xAxis',{'categories':chatLog})
	drawChart(options_area,H_area,'area',emotions,'output_charts_area')
Ejemplo n.º 25
0
def hc_line_time_series(data, title, y_title=None, theme=None, xl_dates=False):
    """Plots a 2d array of times and data points."""
    # Convert Excel dates to datetimes if necessary
    if xl_dates:
        to_date = get_type_converter("var", "datetime")
        data = [(to_date(d), v) for d, v in data]

    H = Highchart()

    H.set_options('chart', {
        'zoomType': 'x'
    })

    H.set_options('xAxis', {
        'type': 'datetime'
    })

    H.set_options('yAxis', {
        'title': {
            'text': y_title or "Values"
        }
    })

    H.set_options('title', {
        'text': title or "Time Series"
    })

    H.set_options('legend', {
        'enabled': False
    })

    H.add_data_set(data, 'area')

    H.set_options('plotOptions', {
        'area': {
            'fillColor': {
                'linearGradient': { 'x1': 0, 'y1': 0, 'x2': 0, 'y2': 1},
                'stops': [
                    [0, "Highcharts.getOptions().colors[0]"],
                    [1, "Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')"]
                ]},
            'marker': {
                'radius': 2
            },
            'lineWidth': 1,
            'states': {
                'hover': {
                    'lineWidth': 1
                }
            },
            'threshold': None
        }
    })

    return hc_plot(H, title, theme)
Ejemplo n.º 26
0
                 'Control: ' + event.ctrlKey + '\\n' + 'Shift: ' + event.shiftKey + '\\n');}"
    },
    dashStyle='ShortDash')
"""
Set up highchart options using 
1. set_options method:  
    set_options(option_type, option_dict)
    option_type is the keyword for highchart options
    option_dict is (python) dict for option settings
    (for option details please ref to highcharts API: http://api.highcharts.com/highcharts#)
"""
H.set_options('chart', {
    'resetZoomButton': {
        'relativeTo': 'plot',
        'position': {
            'x': 0,
            'y': -30
        }
    }
})
H.set_options('xAxis', {'events': {'afterBreaks': 'function(e){return}'}})
H.set_options('tooltip', {'formatter': 'default_tooltip'})
H.set_options('xAxis', {'events': {'pointBreak': 'function(e){return}'}})
H.set_options('chart', {
    'style': {
        'fontFamily': 'Lucida Grande, sans-serif',
        "fontfontSize": '12px'
    }
})
H.set_options('chart', {'style': {"fontfontSize": '22px'}})
H.set_options('chart', {'resetZoomButton': {'position': {'x': 10}}})