示例#1
0
def create_dateline(timeseries, plot_name="", as_title=False):
    """
    timeseries: A list of tuples. Tuple : (datetime object, integer)
    Should either be in increasing or decreasing order
    """
    if as_title:
        dateline = pygal.DateTimeLine(x_label_rotation=25,
                                      x_value_formatter=lambda dt: dt.strftime('%b %Y'),
                                      title=plot_name)
    else:
        dateline = pygal.DateTimeLine(x_label_rotation=25,
                                      x_value_formatter=lambda dt: dt.strftime('%b %Y'))

    # Calculate x_labels
    x_labels = []

    months_span = abs((timeseries[-1][0] - timeseries[0][0]).days//30) + 1
    # print(months_span)
    start_date = min(timeseries[0][0], timeseries[-1][0])
    x_labels.append(start_date)
    _next_date = start_date
    for _ in range(months_span):
        _next_date += datetime.timedelta(days=30)
        x_labels.append(_next_date)

    # More than 10 x_labels gets hard to read, so space them out
    if len(x_labels) > 10:
        new_x_labels = []
        new_x_labels.append(x_labels[0])

        jump_length = (len(x_labels) - 2)//(10 - 2) # Two fixed labels are the first and last
        index = jump_length + 1
        while(index < len(x_labels) - 1):
            new_x_labels.append(x_labels[index])
            index += jump_length

        new_x_labels.append(x_labels[-1])

        dateline.x_labels = new_x_labels
    else:
        dateline.x_labels = x_labels

    if as_title:
        dateline.add("", timeseries)
    else:
        dateline.add(plot_name, timeseries)

    return dateline
示例#2
0
def home():
    try:
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='73.158.191.112',
                                      database='inetSpeed')  # 73.158.191.112

        cursor = cnx.cursor()
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        past = (datetime.now() -
                timedelta(hours=24)).strftime('%Y-%m-%d %H:%M:%S')

        cursor.execute(
            "SELECT date_time, speed_down, speed_up FROM inetLog WHERE date_time BETWEEN %s AND %s",
            (past, now))
        # cursor.execute("SELECT datetime, speed_down, speed_up FROM inetLog WHERE datetime BETWEEN %s AND %s;", (past, now))

        downData = list()
        upData = list()
        for i in cursor:
            downData.append((i[0], i[1]))
            upData.append((i[0], i[2]))

        line_chart = pygal.DateTimeLine(
            x_label_rotation=75,
            truncate_label=-1,
            x_value_formatter=lambda dt: dt.strftime('%m-%d %H:%M'))
        line_chart.add("Down Ave Hour", downData)
        line_chart.add("Up", upData)
        return line_chart.render_response()
    except Exception:
        return (str(Exception))
示例#3
0
文件: bot.py 项目: alimogh/overwatch
    def get_placed_orders_chart(self, hours=48):
        bid_points = []
        ask_points = []

        placed_orders = self.botplacedorder_set.filter(
            time__gte=now() - datetime.timedelta(hours=hours)).exclude(
                price_usd__isnull=True).order_by('time')

        for order in placed_orders:
            if order.order_type == 'sell':
                ask_points.append((order.time, order.price_usd))

            if order.order_type == 'buy':
                bid_points.append((order.time, order.price_usd))

        datetimeline = pygal.DateTimeLine(
            x_label_rotation=35,
            x_title='Date',
            y_title='Price (USD)',
            truncate_label=-1,
            legend_at_bottom=True,
            value_formatter=lambda x: '${:.8f}'.format(x),
            x_value_formatter=lambda dt: dt.strftime('%Y-%m-%d %H:%M:%S'),
            style=CleanStyle(font_family='googlefont:Raleway', ),
        )
        datetimeline.add("Buy", bid_points, dots_size=2)
        datetimeline.add("Sell", ask_points, dots_size=2)
        return datetimeline.render_data_uri()
示例#4
0
def graph_temperature():
    chart_list = []
    graph_data = None
    sensor_name_list, start, end, group_by, function_list, sensor_type, group_by_prefix = _get_interval(
        request.args)
    config = __config_graph("{} by {}".format(sensor_type, group_by), start,
                            end)
    config.x_value_formatter = lambda dt: dt.strftime('%S')
    datetimeline = pygal.DateTimeLine(config=config)
    for sensor_name in sensor_name_list.split(';'):
        for function in function_list:
            records = _get_sensor_records(group_by, function, sensor_name,
                                          start, end, sensor_type,
                                          group_by_prefix)
            # if len(records) > 20:
            #    datetimeline.show_minor_x_labels = False
            #    datetimeline.x_labels_major_every = abs(len(records)/20)
            serie = []
            for i in records:
                serie.append((100 * i.prefix + i.date, i.value))
            datetimeline.add(
                "{} [{}]".format(sensor_name,
                                 function._FunctionGenerator__names[0]), serie)
    graph_data = datetimeline.render_data_uri()
    chart_list.append(graph_data)
    result = render_template('chart/chart-generic.html', chart_list=chart_list)
    return result, 'buba mica buba mare'
示例#5
0
def plotBalanceVsTime(data, outDir):
    """
    Plots the total balance against time for multiple lines where each line
    represents a category within the data.

    :param data: A list containing a title and a DataFrame object for each
    category.
    :param outDir: The output directory to store the generated plot file.
    """
    # Initialising beautiful plot format
    config = pygal.Config()
    config.human_readable = True
    config.legend_at_bottom = True
    config.x_label_rotation = 35
    config.x_value_formatter = lambda dt: dt.strftime('%Y-%m-%d')
    config.value_formatter = lambda y: "{:.0f} GBP".format(y)
    config.title = "Immediate Expense Vs Time"

    plot = pygal.DateTimeLine(config)

    def prepareDFPlot(df):
        plotData = []
        for i, row in df.iterrows():
            d = row["DATES"]
            b = row["AMOUNT"]
            plotData.append((d, b))
        return plotData

    # Preparing all data frames for plotting
    for title, df in data:
        plot.add(title, sorted(prepareDFPlot(df)))

    # Save the plot to a file
    plot.render_to_file(os.path.join(outDir, 'balance_vs_time.svg'))
示例#6
0
    def get_rank_chart(self):
        """
        Use Pygal to generate a chart of the rank movements
        :return:
        """
        ranks = [(now(), self.rank)]

        for match in self.matches.order_by('-played'):
            if self.user == match.winner:
                ranks.insert(0, (match.played, match.winner_rank))
            else:
                ranks.insert(0, (match.played, match.loser_rank))

            if self.user == match.challenger:
                ranks.insert(0, (match.played, match.challenger_rank))
            else:
                ranks.insert(0, (match.played, match.opponent_rank))

        chart = pygal.DateTimeLine(
            title='Rank Movements',
            x_label_rotation=35,
            x_title='Date Played',
            y_title='Rank',
            range=(1, UserProfile.objects.filter(active=True).aggregate(
                max_rank=Max('rank'))['max_rank']),
            inverse_y_axis=True,
            show_legend=False,
            truncate_label=-1,
            x_value_formatter=lambda dt: dt.strftime('%b. %d, %Y, %I:%M %p'),
            style=CleanStyle(font_family='googlefont:Raleway', ),
        )
        chart.add('', ranks)
        return chart.render_data_uri()
示例#7
0
    def get_graph(self):
        data = self.get_data()
        if data:
            max_value = max([value[1] for value in data if value[1] is not None])
        else:
            max_value = 0.5

        my_style = DefaultStyle()
        my_style.font_family = 'googlefont:Roboto'
        my_style.foreground = 'black'
        my_style.foreground_strong = 'white'
        my_style.title_font_size = 18
        my_style.background = "#4285f4"

        if max_value <= 1 and max_value >= 0.5:
            my_range = (0, 1)
        else:
            my_range = (0, max_value * 2)
        graph = pygal.DateTimeLine(
            x_value_formatter=lambda dt: dt.strftime('%d.%m.%Y, %H:%M:%S'),
            range=my_range,
            title="{} \n From {} to {}".format(self.field_name, self.start, self.end),
            style = my_style,
            show_legend = False,
            interpolate = 'cubic',
            dots_size=2
        )
        graph.add(self.field, data)
        return graph.render_django_response()
示例#8
0
def display_HddGraph(strMac, argGraph):
    # Récupére les infos de la BDD concernant cette adresse MAC
    rowsMbTotal = str_to_dateTime(bddH.getHddMbTotalByMac(strMac))
    rowsMbUse = str_to_dateTime(bddH.getHddMbUseByMac(strMac))
    rowsPcUse = str_to_dateTime(bddH.getHddPcUseByMac(strMac))

    # Initialise les données du graph
    graph = pygal.DateTimeLine(
        x_label_rotation=35,
        truncate_label=-1,
        x_value_formatter=lambda dt: dt.strftime(DATE_PATTERN))
    if argGraph == 'e':
        graph.add("Total (Mb)", rowsMbTotal)
        graph.add("Utilisation (Mb)", rowsMbUse)
    elif argGraph == 'r':
        graph.add("Utilisation (%)", rowsPcUse)
    else:
        graph.add("Total (Mb)", rowsMbTotal)
        graph.add("Utilisation (Mb)", rowsMbUse)
        graph.add("Utilisation (%)", rowsPcUse)

    # Display graph
    path_img = TMP_FOLDER + '/graph.png'
    graph.render_to_png(path_img)
    subprocess.call(["eog", path_img])
示例#9
0
def plot_timeseries_pygal(dates, allseries, key, title, region):
    datetimeline = pygal.DateTimeLine(
        x_label_rotation=35,
        truncate_label=-1,
        title=f"COVID {title}",
        x_title=None,
        y_title=None,
        height=300,
        show_x_guides=True,
        show_y_guides=False,
        x_value_formatter=lambda dt: dt.strftime('%b %d'))

    # Don't add title (1st arg) here: it adds it as a legend on the left side
    # which then messes up the alignment of the three charts.
    datetimeline.add(None, list(zip(dates, allseries[key])))

    datetimeline.x_labels = date_labels(dates[0], dates[-1])

    outfile = f'{DATA_DIR}/covid-{key}-{region}.svg'

    # datetimeline.render_to_file(outfile)
    svg = datetimeline.render()

    # pygal loads a script from github and has no option to change that.
    # https://github.com/Kozea/pygal/issues/351
    # Load it locally instead
    evil_redirect = b'https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js'
    svg = svg.replace(evil_redirect, b'pygal-tooltips.min.js')
    with open(outfile, 'wb') as outfp:
        outfp.write(svg)

    if verbose:
        print("Saved to", outfile)
示例#10
0
文件: charts.py 项目: vonabarak/felis
    def get(self, request, pk, attribute, **kwargs):
        import pygal
        from pygal.style import DarkSolarizedStyle

        object = Model.objects.get(pk=pk)
        chartline = pygal.DateTimeLine(
            x_label_rotation=35, truncate_label=-1, style=DarkSolarizedStyle, fill=True,
            x_value_formatter=lambda dt: dt.strftime('%d, %b %Y at %I:%M:%S %p'),
        )
        fieldname = 'rctl_' + attribute
        dots = [
            (i.created, i.value[fieldname])
            for i
            in Transaction.objects.filter(
                instance=object,
                created__gt=timezone.now() - timedelta(hours=6)
            ).order_by('id')
            if (fieldname in i.value) and (i.value[fieldname] is not None)
            ]
        dots.append((timezone.now(), object.as_dict()[fieldname]))
        chartline.add(attribute, dots)
        for rule in RctlRule.objects.filter(jail=object, resource=attribute).all():
            chartline.add(
                rule.action,[(timezone.now()-timedelta(hours=6), rule.amount), (timezone.now(), rule.amount)]
            )
        return http.HttpResponse(chartline.render(), content_type='image/svg+xml')
示例#11
0
 def _make_chart(self, filepath, title, data):
     datetimeline = pygal.DateTimeLine(
         x_label_rotation=35,
         truncate_label=-1,
         x_value_formatter=lambda dt: dt.strftime('%d, %b %Y'))
     datetimeline.title = title
     datetimeline.add('', data)
     datetimeline.render_to_file(filepath)
示例#12
0
def generate_graph(filename, hostname, info, categories):
    datetimeline  = pygal.DateTimeLine(x_label_rotation=35, title=hostname)

    for category in categories:
        if category in info:
            i = [(date, i) for date, i in zip(info['dates'], info[category])]
            datetimeline.add(category, i)

    datetimeline.render_to_file(filename)
示例#13
0
def plot_timeseries_pygal(key, loclist):
    locnames = ", ".join([l["county"] for l in loclist])
    tot = sum([covid_data[l['locationID']][key][-1] for l in loclist])
    # Integer or float?
    if int(tot) == tot:
        title = f"{tot} {key} in {locnames}"
    else:
        # XXX Is there a way to say "no more than 2 decimal places"
        # while leaving an option for less?
        title = f"{tot:.2f} {key} in {locnames}"

    datetimeline = pygal.DateTimeLine(
        x_label_rotation=35,
        truncate_label=-1,
        title=title,
        x_title=None,
        y_title=None,
        height=300,
        show_x_guides=True,
        show_y_guides=False,
        x_value_formatter=lambda dt: dt.strftime('%b %d'))

    # Don't add title (1st arg) here: it adds it as a legend on the left side
    # which then messes up the alignment of the three charts.
    for locdict in loclist:
        locID = locdict["locationID"]

        # The first argument to add() is the name of the plot,
        # which will be used for the legend.
        # But for a single county, the legend just takes away space
        # from the plot and doesn't add anything, so make the name
        # empty in that case.
        if len(loclist) > 1:
            locname = locdict["county"]
            if locname.endswith(" County"):
                locname = locname[:-7]
        else:
            locname = None
        datetimeline.add(locname, list(zip(dates, covid_data[locID][key])))

    datetimeline.x_labels = date_labels(dates[0], dates[-1])

    outfile = f'{DATA_DIR}/covid-{key}.svg'

    # datetimeline.render_to_file(outfile)
    svg = datetimeline.render()

    # pygal loads a script from github and has no option to change that.
    # https://github.com/Kozea/pygal/issues/351
    # Load it locally instead
    evil_redirect = b'https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js'
    svg = svg.replace(evil_redirect, b'pygal-tooltips.min.js')
    with open(outfile, 'wb') as outfp:
        outfp.write(svg)

    if verbose:
        print("Saved to", outfile)
def prepare_readings_chart(attribute, attribute_name, readings, x_label_count, y_min, y_max, x_label, y_label, line_colour, logarithmic):
    style = Style(font_family="Arial",  colors=[line_colour], background='transparent')
    temp_chart = pygal.DateTimeLine(x_label_rotation=20, range=(y_min, y_max),
                               show_minor_x_labels=False, show_major_x_labels=True,
                               x_labels_major_count=x_label_count, show_legend=False, style=style,
                                    x_title=x_label, y_title=y_label, logarithmic=logarithmic,
                                    x_value_formatter=lambda dt: dt.strftime('%H:%M %p'))
    temp_chart.add(attribute_name, [(datetime.fromtimestamp(i.time), getattr(i, attribute)) for i in readings])
    chart = temp_chart.render_data_uri()
    return chart
示例#15
0
 def __init__(self):
     self.chart = pygal.DateTimeLine(
         title='Quotes over Time',
         x_label_rotation=90,
         x_value_formatter=lambda dt: dt.strftime('%b %Y'),
         margin=20,
         show_legend=False,
         show_dots=False,
         fill=True,
         style=style)
示例#16
0
    def pygal_graph(self):

        self.datetimeline = pygal.DateTimeLine()
        #self.datetimeline.add("Serie", self.df[1])
        #self.datetimeline.add("Serie2", self.dataFrame()[2].replace({pd.np.nan: None}))

        #self.datetimeline.add("Serie2", self.dataFrame()[2])
        self.datetimeline.add("Seriet",
                              [(self.df[1]),
                               self.dataFrame()[2].replace({pd.np.nan: None})])
        return self.datetimeline
示例#17
0
    def get_date_xy_chart(self, **kwargs):
        default_data = {}
        default_path = 'date_xy_chart.svg'
        data = kwargs.pop('data', default_data)
        path = kwargs.pop('path', default_path)
        datetimechart = pygal.DateTimeLine(stroke=False, dots_size=10)
        for category in data:
            datetimechart.add(category, data[category])

        datetimechart.render_to_file(path)

        return path
示例#18
0
文件: app.py 项目: CCLDArjun/Quizer
def get_graph_data():
	graph = pygal.DateTimeLine(x_label_rotation=35, truncate_label=-1)
	for x in range(1, len(User.query.all())+1):
		if Solved.query.filter_by(user_id=x).first() is None:
			continue
		data = [(User.query.filter_by(id=x).first().date_created, 0)]
		for y in range(1, len(list(Solved.query.filter_by(user_id=x)))+1):
			row = Solved.query.filter_by(user_id=x)[y-1]
			data.append((row.timestamp, float(Challenge.query.filter_by(id=row.channel_id).first().points)+float(data[y-1][1])))
		graph.add(User.query.filter_by(id=x).first().username, data)
	graph_data = graph.render_data_uri()
	return graph_data
示例#19
0
    def gyroscope(self):
        """ the gravity page """
        from datetime import datetime, timedelta
        date_chart = pygal.DateTimeLine(x_label_rotation=20)
        mydata = self.get_data_upper("Gyroscope")
        print(mydata)
        date_chart.add("Gyroscope", mydata)
        output = date_chart.render().decode()

        template = JINJA_ENVIRONMENT.get_template('gyroscope.html')
        template_values = {"graph": output}
        return template.render(template_values)
示例#20
0
def plot_data(series, labels, is_cpu=False):
    line_chart = pygal.DateTimeLine(
        x_label_rotation=35,
        truncate_label=-1,
        x_value_formatter=lambda dt: dt.strftime('%d/%m/%Y - %H:%M:%S'),
        show_dots=False)

    line_chart.title = 'CPU' if is_cpu else 'Memory'
    for idx, val in enumerate(series):
        line_chart.add(labels[idx], val)
    # line_chart.render_to_png('cpuGraph.png' if is_cpu else 'memoryGraph.png')
    line_chart.render_in_browser()
示例#21
0
    def _render_chart(chart: _Chart, chart_type: str, fields: list,
                      datas: list):
        options = {}

        if chart.title == "Multi-tablers" and chart_type == 'last_24':
            pyg_chart = pygal.StackedLine()
        elif chart_type in ['spark', 'last_24']:
            pyg_chart = pygal.DateTimeLine()
        else:
            pyg_chart = pygal.Bar()

        if chart_type == 'spark':
            pyg_chart.fill = True
            pyg_chart.width = 100
            pyg_chart.height = 20
            pyg_chart.show_dots = False
            pyg_chart.show_legend = False
            pyg_chart.show_x_labels = False
            pyg_chart.show_y_labels = False
            pyg_chart.spacing = 0
            pyg_chart.margin = 0
            pyg_chart.min_scale = 1
            pyg_chart.max_scale = 2
            pyg_chart.explicit_size = True
            pyg_chart.no_data_text = ''
            pyg_chart.js = ()
        elif chart_type == 'last_24':
            pyg_chart.title = chart.title
            pyg_chart.fill = True
            pyg_chart.show_dots = False
            pyg_chart.legend_at_bottom = True
            pyg_chart.show_x_guides = True
            pyg_chart.spacing = 20
            pyg_chart.margin = 20
            pyg_chart.x_label_rotation = 45
            pyg_chart.x_labels_major_count = 15
            pyg_chart.x_value_formatter = lambda dt: dt.strftime('%H:%M')
            pyg_chart.show_minor_x_labels = False
        elif chart_type == 'by_hour':
            pyg_chart.title = chart.title
            pyg_chart.x_labels = [value[0] for value in datas[0]]
        else:
            pyg_chart.title = chart.title
            pyg_chart.x_labels = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']

        for field, data in zip(fields, datas):
            if chart_type in ['spark', 'last_24']:
                pyg_chart.add(field.label, data)
            else:
                pyg_chart.add(field.label, [value[1] for value in data])

        return pyg_chart.render(is_unicode=True)
示例#22
0
    def lineara(self):
        """ the Linear Acceleration page """

        from datetime import datetime, timedelta
        date_chart = pygal.DateTimeLine(x_label_rotation=20)
        mydata = self.get_data_upper("Accelerometer")
        print(mydata)
        date_chart.add("Linear Acceleration", mydata)
        output = date_chart.render().decode()

        template = JINJA_ENVIRONMENT.get_template('lineara.html')
        template_values = {"graph": output}
        return template.render(template_values)
def linechart():
    '''plots line chart'''
    xy_chart = pygal.DateTimeLine(x_label_rotation=35, show_legend=False)
    xy_chart.title = "/r/singapore daily thread comment count 1st Jan - 6 Mar 18"
    xy_chart.x_title = "Date"
    xy_chart.y_title = "Comments"
    #create list of dict for values to plot
    values = []
    for index, item in df.iterrows():
        value = (item['created_utc'], item['num_comments'])
        label = 'Score: {0}'.format(item['score'])
        values.append({'value': value, 'label': label, 'xlink': item['url']})
    xy_chart.add('series', values)
    xy_chart.render_in_browser()
def scatter():
    '''plots scatter chart'''
    xy_chart = pygal.DateTimeLine(stroke=False,
                                  show_legend=False,
                                  x_label_rotation=35)
    xy_chart.title = "/r/singapore daily thread post count 1st Jan - 6 Mar 18"
    xy_chart.x_title = "Date"
    xy_chart.y_title = "Comments"
    for index, item in df.iterrows():
        xy_chart.add(item['created_utc'],
                     [{
                         'value': (item['created_utc'], item['num_comments']),
                         'label': 'Score: {0}'.format(item['score']),
                         'xlink': item['url']
                     }])
    xy_chart.render_in_browser()
示例#25
0
def plot_profit_history(device_id, device_profit_history):
    line_chart = pygal.DateTimeLine(
        x_label_rotation=35,
        truncate_label=-1,
        x_value_formatter=lambda dt: dt.strftime('%d, %b %Y'),
        show_dots=False,
        y_title='USD/Day')
    line_chart.title = 'Device {} Profit'.format(device_id)

    max_profits = defaultdict(int)
    for coin in device_profit_history:
        line_chart.add(coin, device_profit_history[coin])
        for t, p in device_profit_history[coin]:
            max_profits[t] = max(max_profits[t], p)
    line_chart.add('Max Profit',
                   sorted(list(max_profits.items()), key=lambda x: x[0]))
    line_chart.render_to_file('profit_{}.html'.format(device_id))
示例#26
0
def chartTimedData(data, username=""):

    chart = pygal.DateTimeLine(
        fill=True,
        show_legend=False,
        show_x_labels=False,
        show_y_labels=False,
        width=1024,
        x_label_rotation=25,
        truncate_label=-1,
        x_value_formatter=lambda dt: dt.strftime('%m/%d/%y-%Hh%M'),
        style=pygal.style.LightStyle)
    chart.add("block weight % / Ѧ1000 vote",
              [(d, round(1000 * 100 * v, 4)) for d, v in data])

    chart.render_to_file(
        os.path.join(zen.ROOT, "app", "static", "ctd_%s.svg" % username))
示例#27
0
 def render_chart(environ, start_response):
     data = list(bp_perf._block_summaries)
     series_data = defaultdict(lambda: defaultdict(list))
     for summary in data:
         time_slot = _round_timestamp(summary.timestamp, 10)
         series_data[summary.producer][time_slot].append(not summary.produced)
     chart = pygal.DateTimeLine(width=1200, height=600)
     chart.title = "Missed Slots"
     for producer, series in series_data.items():
         chart.add(
             producer,
             [
                 (time_slot, 100 * sum(missed) / len(missed))
                 for time_slot, missed in series.items()
             ]
         )
     start_response('200 OK', [('content-type', 'image/svg+xml')])
     return [chart.render()]
示例#28
0
def create_popularity_chart(domain):

    line_chart = pygal.DateTimeLine(
        x_label_rotation=45,
        height=200,
        width=1000,
        x_value_formatter=lambda dt: dt.strftime('%b %d, %Y'))

    line_chart.title = "Number of top 1000 GitHub projects using this library on given date"

    end_date = MetricsEntry.objects.latest('created_on').created_on
    start_date = end_date - relativedelta(years=1)

    libraries = domain.libraries.all(
    )  #('created_on')# data_set.filter(run_time__gte=start_date).filter(run_time__lte=end_date).order_by('year').order_by('month')

    domain_dic = {}
    for library in libraries:
        metrics = library.metrics.filter(created_on__gte=start_date).filter(
            created_on__lte=end_date).order_by('created_on')

        if metrics == None:
            continue

        for metric in metrics:

            if library.name in domain_dic.keys():
                domain_dic[library.name].append(
                    (metric.created_on.date(), metric.popularity))
            else:
                popularity_data_arr = []
                popularity_data_arr.append(
                    (metric.created_on.date(), metric.popularity))
                domain_dic[library.name] = popularity_data_arr

    #line_chart.x_labels = map(str, create_date_range(start_date,end_date))

    for key, value in domain_dic.items():
        line_chart.add(key, value)

    data = line_chart.render_data_uri()
    saveData(data, domain.name + '_popularity_chart.pkl')

    save_chart_in_db(line_chart, domain, metric_name="popularity")
示例#29
0
文件: charts.py 项目: vonabarak/felis
    def get(self, request, pk, **kwargs):
        import pygal
        from pygal.style import DarkSolarizedStyle
        chartline = pygal.DateTimeLine(
            x_label_rotation=35, truncate_label=-1, style=DarkSolarizedStyle, logarithmic=True,
            x_value_formatter=lambda dt: dt.strftime('%d, %b %Y at %I:%M:%S %p'), dots_size = 1,
            interpolate='hermite', interpolation_parameters={'type': 'cardinal', 'c': .75},
        )
        object = Model.objects.get(pk=pk)

        used = [
            (i.created, i.value['used'])
            for i
            in Transaction.objects.filter(
                instance=object,
                created__gt=timezone.now() - timedelta(hours=3)
            ).order_by('id')
            if hasattr(i, 'value') and 'used' in i.value and i.value['used'] is not None
            ]
        used.append((timezone.now(), object.used))
        avail = [
            (i.created, i.value['avail'])
            for i
            in Transaction.objects.filter(
                instance=object,
                created__gt=timezone.now() - timedelta(hours=3)
            ).order_by('id')
            if hasattr(i, 'value') and 'avail' in i.value and i.value['avail'] is not None
            ]
        avail.append((timezone.now(), object.avail))
        refer = [
            (i.created, i.value['refer'])
            for i
            in Transaction.objects.filter(
                instance=object,
                created__gt=timezone.now() - timedelta(hours=3)
            ).order_by('id')
            if hasattr(i, 'value') and 'refer' in i.value and i.value['refer'] is not None
            ]
        refer.append((timezone.now(), object.refer))
        chartline.add('USED', used, fill=True)
        chartline.add('AVAIL', avail, fill=True)
        chartline.add('REFER', refer, fill=True)
        return http.HttpResponse(chartline.render(), content_type='image/svg+xml')
示例#30
0
def main():
    temps = []
    config = SafeConfigParser()
    config.read('config.ini')
    fetch_hours = float(config.get('MAIN', 'WEB_UI_HOURS'))
    db = sqlite3.connect(database_file)
    cursor = db.cursor()
    cursor.execute(
        '''
        SELECT * FROM Temps WHERE timestamp > ? ORDER BY timestamp DESC
    ''', (int(time.time()) - int(fetch_hours * 60 * 60), ))
    current_temps = None
    inside_temps = []
    outside_temps = []
    for row in cursor:
        date = datetime.fromtimestamp(row[3])
        date_string = date.strftime("%Y/%m/%d - %H:%M")
        inside_temps.append((date, row[1]))
        outside_temps.append((date, row[2]))
        if current_temps is None:
            current_temps = [str(row[1]), str(row[2])]
        temps.append(
            dict(temp_in=str(row[1]), temp_out=str(row[2]), date=date_string))
    table = TempsTable(temps)
    threshold_temp_low = float(config.get('MAIN', 'THRESHOLD_TEMP_LOW'))
    threshold_temp_high = float(config.get('MAIN', 'THRESHOLD_TEMP_HIGH'))
    graph = pygal.DateTimeLine(
        width=1000,
        height=500,
        legend_at_bottom=True,
        show_dots=False,
        style=DefaultStyle,
        x_value_formatter=lambda dt: dt.strftime('%H:%M'))
    graph.y_labels_major = [threshold_temp_low, threshold_temp_high]
    graph.add("Inside Temp (\u2109)", inside_temps)
    graph.add("Outside Temp (\u2109)", outside_temps)
    graph_data = graph.render_data_uri()
    return render_template(
        "index.html",
        inside_temp="None" if current_temps is None else current_temps[0],
        outside_temp="None" if current_temps is None else current_temps[1],
        graph_data=graph_data,
        table=table.__html__())