Пример #1
0
def plot3():
    p = figure(title='something', x_axis_label='date', x_axis_type='datetime')
    df = pd.read_csv('chart.csv')
    df3 = pd.read_csv('df3d.csv')
    output_file("stacked_bar.html")
    p = Bar(df3,
            label='Country',
            values='Population wo access water',
            stack='category',
            color=color(columns='category',
                        palette=['Orange', 'Red'],
                        sort=False),
            legend='top_right')

    script, div = components(p)
    df4 = df[df['status'] == 'water supplier']
    output_file("bar.html")
    q = Bar(df4,
            label='Country',
            values='Possible water provider',
            legend=False,
            color="Green")
    script2, div2 = components(q)
    return render_template('plot3.html',
                           script=script,
                           div=div,
                           script2=script2,
                           div2=div2)
Пример #2
0
    def plot_scores2(self):

        if self.scores is None:
            return None

        scores = np.vstack(self.scores)
        data = OrderedDict()
        for i in xrange(len(self.class_labels)):
            data[self.class_labels[i]] = scores[:2, i]
        s1 = Bar(data,
                 cat=['precision', 'recall'],
                 title="Per Class Scores",
                 width=500,
                 height=500,
                 legend=True,
                 tools="pan,resize,box_zoom,hover,save,reset")

        data = OrderedDict()
        for i in xrange(len(self.class_labels)):
            data[self.class_labels[i]] = scores[3:4, i]
        s2 = Bar(data,
                 cat=['support'],
                 title="Support",
                 width=500,
                 height=500,
                 legend=True,
                 tools="pan,resize,box_zoom,hover,save,reset")

        p = hplot(s1, s2)

        script, div = components(p)
        return (script, div)
Пример #3
0
 def goChart(label, stack_or_group, values, ylabel=None, color=None):
     convertPDFDate(workingPDF, keyFields[0])
     if ylabel is None:
         ylabel=values
     label=label if isinstance(label, (list, tuple)) else [label]
     if stacked:
         charts.append( Bar(workingPDF, label=CatAttr(columns=label, sort=False), stack=stack_or_group, color=color, values=values, legend=self.showLegend(), ylabel=ylabel))
     else:
         charts.append( Bar(workingPDF, label=CatAttr(columns=label, sort=False), group=stack_or_group, color=color, values=values, legend=self.showLegend(), ylabel=ylabel))
Пример #4
0
def draw_regional_fig_bokeh(make, model, year):
    """
    Returns a bar graph figure rendered in Bokeh; for cars similar to the given
    car, groups price and mileage according to region in greater Boston
    """
    try:
        min_auto_year = int(year) - 2
        max_auto_year = int(year) + 2
    except:
        min_auto_year = 2012
        max_auto_year = 2016

    listings = get_listings(make, model, year)

    df = pd.DataFrame(data=listings)
    if len(df) == 0: return row()  #"No results found, check your spelling"
    df['mileage'] = df.apply(lambda row: get_mileage(row['description']),
                             axis=1)
    df['price'] = df.apply(lambda row: get_price(row['price']), axis=1)
    df['region'] = df['link'].str[1:5]
    df['year'] = df.apply(lambda row: get_year(row['description']), axis=1)
    df['full_region'] = df.apply(
        lambda row: region_dict[row['region'].strip('/')]
        if row['region'].strip('/') in region_dict else None,
        axis=1)
    mileage_count = len(df[df['mileage'].notnull()])

    title1 = 'Average Price of Used {0} {1}, {2}-{3}, by region, n={4}'.format(
        make, model, min_auto_year, max_auto_year, len(df))
    title2 = 'Average Mileage of Used {0} {1}, {2}-{3}, by region, n={4}'.format(
        make, model, min_auto_year, max_auto_year, mileage_count)
    bar1 = Bar(df,
               label='full_region',
               values='price',
               agg='mean',
               title=title1,
               legend=None,
               xlabel="Region",
               ylabel="Price",
               y_range=(0, 20000))
    bar2 = Bar(df,
               label='full_region',
               values='mileage',
               agg='mean',
               title=title2,
               legend=None,
               xlabel="Region",
               ylabel="Mileage",
               y_range=(0, 150000),
               color='dodgerblue')
    return row(bar1, bar2)
Пример #5
0
def author_frequency_barplot(nb_top_ners=50, tf=True):
    if tf:
        output_file('../figures/tf_authors.html')
        ner_freqs = pickle.load(open('../workspace/tf.m', "rb"))
    else:
        output_file('../figures/df_authors.html')
        ner_freqs = pickle.load(open('../workspace/df.m', "rb"))

    top_ners = [w for w, _ in ner_freqs.most_common(nb_top_ners)]
    top_freqs = [c for _, c in ner_freqs.most_common(nb_top_ners)]

    names = []
    for name in top_ners:
        name = name.replace('*', '')
        if '(' in name:
            name = name.split('(')[0].strip()
        name = ' '.join([n.lower().capitalize() for n in name.split('_')])
        name = ''.join([
            c for c in unicodedata.normalize('NFKD', name)
            if not unicodedata.combining(c)
        ])
        names.append(name)

    data = pd.DataFrame({'values': top_freqs[:25], 'labels': names[:25]})
    bar1 = Bar(data,
               label=CatAttr(columns=['labels'], sort=False),
               values='values',
               title='Author Frequency (1-25)',
               width=800,
               height=400)
    xaxis = bar1.select(dict(type=Axis))[1]
    xaxis.major_label_standoff = 0
    xaxis.major_label_orientation = np.pi / 2
    xaxis.major_label_standoff = 6
    xaxis.major_tick_out = 0

    data = pd.DataFrame({'values': top_freqs[25:50], 'labels': names[25:50]})
    bar2 = Bar(data,
               label=CatAttr(columns=['labels'], sort=False),
               values='values',
               title='Author Frequency (25-50)',
               width=800,
               height=400)
    xaxis = bar2.select(dict(type=Axis))[1]
    xaxis.major_label_standoff = 0
    xaxis.major_label_orientation = np.pi / 2
    xaxis.major_label_standoff = 6
    xaxis.major_tick_out = 0
    p = vplot(bar1, bar2)
    save(p)
Пример #6
0
def main():
    # check recalculation request
    if 'recalculate' in request.args:
        if request.args.get('recalculate') == 'True':
            betalyzer.recalculate()

    # build sector betas bar chart
    sector_betas = betalyzer.df_tickers.groupby('sector')['beta'].mean()
    bk_sector_betas = Bar(sector_betas,
                          plot_width=550,
                          plot_height=400,
                          legend=None)
    bk_sector_betas_script, bk_sector_betas_div = components(bk_sector_betas)

    # build market cap betas bar chart
    mktcap_betas = betalyzer.df_tickers.groupby(
        'market_cap_decile')['beta'].mean()
    bk_mc_betas = Bar(mktcap_betas,
                      plot_width=550,
                      plot_height=400,
                      legend=None)
    bk_mc_betas_script, bk_mc_betas_div = components(bk_mc_betas)

    # build market cap scatter plot
    scatter = Scatter(betalyzer.df_tickers,
                      x='market_cap_log',
                      y='beta',
                      plot_width=550,
                      plot_height=400)
    scatter_script, scatter_div = components(scatter)

    # build line plot for top three stocks
    top_tickers = betalyzer.df_tickers['ticker'].head(3)
    bk_history = Line(betalyzer.df_betas[top_tickers],
                      plot_width=550,
                      plot_height=400)
    bk_history_script, bk_history_div = components(bk_history)

    return render_template(
        'main.html',
        dt_tickers=betalyzer.df_tickers.to_dict(orient='records'),
        bk_sector_betas_script=bk_sector_betas_script,
        bk_sector_betas_div=bk_sector_betas_div,
        bk_mc_betas_script=bk_mc_betas_script,
        bk_mc_betas_div=bk_mc_betas_div,
        scatter_script=scatter_script,
        scatter_div=scatter_div,
        bk_history_script=bk_history_script,
        bk_history_div=bk_history_div)
Пример #7
0
    def createBokehChart(self):
        data = self.getWorkingPandasDataFrame()
        keyFields = self.getKeyFields()
        valueFields = self.getValueFields()

        clusterby = self.options.get("clusterby")
        stacked = self.options.get("charttype", "grouped") == "stacked"
        subplots = self.isSubplot()

        # self.debug("keyF={0}, valueF={1}, cluster={2}, stacked={3}".format(keyFields[0], valueFields[0], clusterby, stacked))
        charts = []
        params = []

        if subplots and len(valueFields) > 1:
            for val in valueFields:
                series = clusterby if clusterby is not None else False
                values = val
                params.append((values, series))
        elif clusterby is not None and len(valueFields) <= 1:
            params.append((valueFields[0], clusterby))
        else:
            series = '_'.join(valueFields)
            values = blend(*valueFields,
                           name=series.replace('_', ','),
                           labels_name=series)
            if clusterby is not None:
                self.addMessage(
                    "Warning: 'Cluster By' ignored when you have multiple Value Fields but subplots option is not selected"
                )
            params.append((values, series))

        for p in params:
            if stacked:
                b = Bar(data,
                        label=keyFields[0],
                        values=p[0],
                        stack=p[1],
                        legend=self.showLegend())
            else:
                b = Bar(data,
                        label=keyFields[0],
                        values=p[0],
                        group=p[1],
                        legend=self.showLegend())

            charts.append(b)

        return charts
Пример #8
0
	def withplotly(self, dfMergeWithInfo):
		import plotly.plotly as py
		import pandas as pd
		from plotly.graph_objs import *
		import plotly 
		plotly.tools.set_credentials_file(username='******', api_key='15EhVCwBDqWBANW8zQ2A')
		data = Data([
		    Bar(
		        x=dfMergeWithInfo["videoSid"],
		        y=dfMergeWithInfo["playCount"]
		    )
		])
		layout = Layout(
		    title='2014 MN Capital Budget',
		    font=Font(
		        family='Raleway, sans-serif'
		    ),
		    showlegend=False,
		    xaxis=XAxis(
		        tickangle=-45
		    ),
		    bargap=0.05
		)
		fig = Figure(data=data, layout=layout)
		plot_url = py.plot(data,filename='MN Capital Budget - 2014')
		py.image.save_as(fig, 'mn-14-budget.png')	
Пример #9
0
def vidEngageDistributionOneVideo(videoID):
    factor = sorted([
        vidEngageUsers[user][i] for user in vidEngageUsers
        for i in vidEngageUsers[user] if i == videoID
    ][:30],
                    reverse=True)
    print factor
    userNames = [
        i[0] for i in sorted([(u.replace('.json', ''), vidEngageUsers[u][j])
                              for u in vidEngageUsers
                              for j in vidEngageUsers[u] if j == videoID][:30],
                             key=lambda x: x[1],
                             reverse=True)
    ]
    hover = HoverTool(tooltips=[
        ("(x,y)", "($x, $y)"),
    ])

    TOOLS = ['resize, save, pan, box_zoom, wheel_zoom', hover]
    output_file("h.html")
    bar = Bar(factor,
              userNames,
              title="Distribution of Video Engagement for ",
              width=1000,
              height=1000,
              ylabel='Video Engagement Factor')
    show(bar)
Пример #10
0
 def _generate_his3_bokeh(self, data_list_bokeh_his3, output_path):
     bars = []
     for data_set in data_list_bokeh_his3:
         bar = Bar(data_set,
                   values='No Reads [nt]',
                   stack='sample',
                   label='Length [nt] of aligned reads',
                   agg='sum',
                   legend='top_left',
                   width=1500,
                   bar_width=1.0,
                   color='Black',
                   tools=[
                       HoverTool(tooltips=[("Read length",
                                            "@x"), ("No of reads",
                                                    "@height")])
                   ],
                   title='Length & Frequency of Aligned Reads')
         bar.legend.background_fill_alpha = 0.5
         bars.append(bar)
     plots = column(*bars)
     html = file_html(plots, CDN, 'Alignment Stats')
     with open(output_path + '/Length & Frequency of Aligned Reads.html',
               'w') as output_bokeh_his3:
         output_bokeh_his3.write(html)
Пример #11
0
    def frequency(self,
                  dataframe,
                  width=None,
                  height=None,
                  palette=None,
                  title="Frequency plot",
                  x_axis_label=None,
                  y_axis_label="Frequency",
                  grid=None):
        palette = self.get_option('palette') if palette is None else palette
        width = self.get_option('width') if width is None else width

        if not height:
            width, height = self.golden_ratio(width, height)

        palette = self._palette(palette, len(dataframe.index))

        bar = Bar(dataframe,
                  color=palette,
                  values='frequency',
                  ylabel=y_axis_label,
                  xlabel=x_axis_label,
                  title=title,
                  width=width,
                  height=height)

        if grid is not None:
            grid.append(bar)
            return grid

        return bar
Пример #12
0
def plotDateGrid(date):
    # Assert given date is available.
    assert date in authorKey(df, 'Capella',
                             'date'), 'No entries for this date.'
    # Create list of fitting dataframes
    tempList = [
        biblioList[s] for s in range(len(biblioList))
        if biblioList[s]['date'][0] in [date]
    ]
    # sort by occuring diagrams
    dfDATE = sorted(tempList,
                    key=lambda tempList: tempList['Count'].sum(),
                    reverse=True)
    plotListDATE = []
    for x in range(len(dfDATE)):
        titleS = dfDATE[x]['biblio'][0] + '; ' + str(
            dfDATE[x]['date'][0]) + ' CE'
        b0 = Bar(dfDATE[x],
                 title=titleS,
                 label='biblio',
                 values='Count',
                 group='diaTyp',
                 bar_width=1,
                 ylabel='Diagrams',
                 palette=viridis(14),
                 width=250,
                 height=250,
                 legend=False)
        b0.xaxis.major_label_orientation = "horizontal"
        b0.xaxis.axis_label = ''
        plotListDATE.append(b0)
    plotGrid = gridplot(plotListDATE, ncols=3)
    show(plotGrid)
Пример #13
0
    def plot_memory_hist(self, mode='overview'):
        # Output to static HTML file
        output_file_name = self.get_output_file_name()
        output_file_name += "_memory_hist_" + mode
        output_file(output_file_name + '.html', title=output_file_name)

        # List of histogram figures
        figures = []
        data_df = []
        for trace in self.traces:
            mem_info = trace.get_memory_hists(mode)
            figures.append(mem_info['hist'])
            data_df.append(mem_info['info'])

        # Plot mean and median comparison bar charts
        bars = []
        for access_type_index in range(len(data_df[0])):
            data_df_list = []
            for index, item in enumerate(data_df):
                data_df_list.append(data_df[index][access_type_index])
            data_dfs = pd.concat(data_df_list)
            access_location = data_dfs['location'][0]
            fig_bar = Bar(data_dfs, values='value', group='sched',
                          color='color', legend='center', label='type',
                          title=access_location + ': Mean and Median',
                          ylabel='Cycles')
            bars.append(fig_bar)
        figures.append(bars)

        # Plot all figures
        plot = gridplot(figures)
        show(plot)
Пример #14
0
def fnCreate_Chart_Bar(df):   
    pd.options.html.border=0
    
    plot = Bar(df, 'Sub_Attbt', values='FY2013', title="Total DISPL by Attribute", bar_width=0.4)
    plot.logo=None
    script, div = components(plot,CDN)    
    return script, div  
Пример #15
0
def traits():
    with open(join(dirname(__file__),
                   '..\\output\\profile.txt')) as personality_text:
        personality_insights = PersonalityInsightsV3(
            version="2017-02-11",
            username="******",
            password="******")
        s = json.dumps(
            personality_insights.profile(text=personality_text.read()),
            indent=2)
        socialAttributes = json.loads(s)
        for item in socialAttributes:
            my_dict = {}
            if isinstance(socialAttributes[item], list):
                for i in socialAttributes[item]:
                    d = {}
                    try:
                        d[i['name']] = i['percentile']
                        sTraits.append(i['name'])
                        percentile.append(i['percentile'])
                    except:
                        pass
            else:
                pass

    d['sTraits'] = sTraits
    d['percentile'] = percentile
    df = pd.DataFrame(d)
    p = Bar(df,
            'sTraits',
            values='percentile',
            title="Social Traits",
            plot_width=1200,
            plot_height=800)
    output_file('index/templates/index/traits.html')
Пример #16
0
def recognize_image():
    img_data = re.sub(r'^data:image/.+;base64,', '', request.form['img'])
    img_bytes = base64.b64decode(img_data)
    img = Image.open(io.BytesIO(img_bytes))
    img = img.split()[3]  # remove alpha

    iarr = np.array(img)
    flat = iarr.flatten()
    threshold(flat)
    clf = joblib.load(os.path.join(CLASSIFIERS_DIR, 'svc.pkl'))
    results = clf.predict([flat])
    prob = clf.predict_proba([flat])[0]
    print (results, clf.decision_function([flat]))
    print (prob, np.where(prob == prob.max()), type(np.where(prob == prob.max())[0][0]))
    # Render chart
    d = {'values': prob}
    df = pd.DataFrame(d)
    p = Bar(df, values='values', label='index', title="SVC predict_proba", legend=False, toolbar_location=None)

    plot_script, plot_div = components(p)

    return jsonify({'status': 'ok',
                    'svc': {'predicted': int(results[0]),
                            'prob': int(np.where(prob == prob.max())[0][0]),
                            'bokeh_js': plot_script,
                            'bokeh_div': plot_div}
                    })
def bar_response(results_list, output_path):

    output_dir = os.path.join(output_path, "charts")
    if os.path.isdir(output_dir) is False:
        os.mkdir(output_dir)

    tools = "pan,wheel_zoom,box_zoom,reset,hover,save"

    for df in results_list:
        print(df)
        p = Bar(df,
                label='hh_type',
                values='perc_res',
                stack='digital',
                title="a_title",
                legend='top_right',
                tools=tools)

        hover = p.select_one(HoverTool)
        hover.point_policy = "follow_mouse"
        hover.tooltips = [
            ("count", "@height"),
        ]
        output_file_path = os.path.join(output_dir, 'test bar.html')
        output_file(output_file_path)
        show(p)
Пример #18
0
 def _plot_bokeh_read_no_per_lib(self, gene_quanti_combined_raw,
                                 data_bokeh_overview):
     try:
         colors = [
             'Black', 'DarkSlateGray', 'MediumVioletRed', 'DarkCyan',
             'Indigo', 'DarkBlue', '#a6cee3', '#1f78b4', '#b2df8a',
             '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00',
             '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'
         ]
     except IndexError:
         sys.stderr.write("Appearently the number of features to be "
                          "plotted exceeds '18'. Exiting\n")
         sys.exit(2)
     plots = []
     for data_set in data_bokeh_overview:
         pl = Bar(data_set,
                  values='Gene count',
                  label='Library',
                  agg='sum',
                  stack='Features_Orientation',
                  palette=colors,
                  tools=[
                      HoverTool(tooltips=[("No of reads", "@height")]),
                      BoxZoomTool(),
                      ResetTool(),
                      PanTool(),
                      WheelZoomTool()
                  ])
         pl.legend.background_fill_alpha = 0.5
         plots.append(pl)
     self._plot_bokeh_correlation(gene_quanti_combined_raw, plots)
Пример #19
0
    def plot_top_topic_of_author_by_year(self, df_author_eval, plot=True):
        '''needs output from plot_author_evolution_plot(a_id) as input
        Plots the top topic of the author for the given year'''

        years = [y for y in range(1987, 2017)]
        dc = df_author_eval.cumsum(axis=1)
        p = [dc[y].idxmax() for y in years]
        if (plot):
            #            plt.bar(years,p)
            #            plt.show()
            df_f = pd.DataFrame({'Years': years, 'TopTopic': p})

            output_file("toptopicbyyear.html")

            pl = Bar(df_f,
                     'Years',
                     values='TopTopic',
                     title="Bar Plot of top Topic",
                     color='blue',
                     legend=False)
            show(pl)
            print("The author changed the topic %d times" % len(np.unique(p)))
            print("\n Following are the topics:")
            for i in np.unique(p):
                print("\nTopic %d" % (i + 1))
                print('\n Top Words:')
                print(self.model.show_topic(i))
                print('\n')

        return p
Пример #20
0
    def topic_evolution_by_year(self, topic, sp=True):
        year_dist = self.year_dist
        topic_score = []
        for i in range(len(year_dist)):
            topic_score.append(year_dist[i].sum()[topic])
        tf = pd.DataFrame({
            'Topic' + str(topic) + 'Score': topic_score,
            'Year': [y for y in range(1987, 2017)]
        })
        #        ax=tf.plot(kind='bar')
        #        ax.set_xticklabels([y for y in range(1987,2017)], rotation=90)
        #        plt.show()
        #
        output_file("topicevolutionbyyear.html")

        p = Bar(tf,
                'Year',
                values='Topic' + str(topic) + 'Score',
                title="Bar Plot of Topic %d score for all years " % topic,
                color='green',
                legend=False)
        if (sp):
            show(p)

        print('\n Following are the top words in topic %d:' % topic)
        print(self.model.show_topic(topic))

        return topic_score, p
Пример #21
0
    def __get_figure_bar(self, dataframe_main, column_name, xlabel, ylabel):
        if not is_all_zeros(dataframe_main[column_name]):
            mean = np.round_(dataframe_main[column_name].mean(), 4)

            # Save to file
            if ENABLE_SEABORN:
                output_file_name = self.__report_file.split('.')[0]
                output_file_name += '_' + xlabel + '_' + column_name + '.eps'

                fig, ax = plt.subplots(1, 1)
                ax.get_xaxis().set_visible(False)

                title = 'Avg: ' + column_name + '=' + str(mean)
                bar_plot = dataframe_main[column_name].plot(ax=ax,
                                                            kind='bar',
                                                            table=True,
                                                            title=title)
                bar_plot.figure.savefig(output_file_name)
                bar_plot.figure.clf()

            # Bokeh draw
            bar_ratio = Bar(dataframe_main,
                            values=column_name,
                            label='ModuleId',
                            xlabel=xlabel,
                            ylabel=ylabel,
                            title='Avg: ' + column_name + '=' + str(mean))
            return bar_ratio
Пример #22
0
def bar_color_by_year():
    df = odo(g.ds, pd.DataFrame)

    df1 = df.groupby(['production_year', 'color'
                      ]).size().reset_index().rename(columns={0: 'count'})
    sums = df.groupby(
        ['production_year',
         'color']).agg('size').reset_index().groupby('production_year').sum()
    df1['prc'] = df1.apply(lambda x: x[2] * 100 / sums.loc[x[0]], axis=1)

    form = CarsRelativeValuesForm(request.args, csrf_enabled=False)

    field = 'prc' if 'submit' in request.args and form.validate(
    ) and form.is_relative.data else 'count'

    p = Bar(
        df1,
        values=field,
        label='production_year',
        stack='color',
        legend=False,  #'top_right',
        title='Colors by Year of production',
        xlabel="Year",
        ylabel="Count",
    )

    p.background_fill_color = "beige"

    return render(p, dict(form=form))
Пример #23
0
def plot_crashes_vs_year(air_data, method, save_fig=True):
    """
                        姣忓勾绌洪毦鏁板垎鏋�
      """
    if method == 'sns':

        # Seaborn 缁樺浘
        plt.figure(figsize=(15.0, 10.0))
        sns.countplot(x='Year', data=air_data)
        # 瑙e喅matplotlib鏄剧ず涓枃闂
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 鎸囧畾榛樿瀛椾綋
        plt.rcParams[
            'axes.unicode_minus'] = False  # 瑙e喅淇濆瓨鍥惧儚鏄礋鍙�-'鏄剧ず涓烘柟鍧楃殑闂
        plt.title(u'绌洪毦娆℃暟  vs 骞翠唤')

        plt.xlabel(u'骞翠唤')
        plt.ylabel(u'绌洪毦娆℃暟')
        plt.xticks(rotation=90)

        if save_fig:
            plt.savefig('crashes_year.png')
        plt.show()

    elif method == 'bokeh':
        # Boken 缁樺浘
        p = Bar(air_data,
                'Year',
                title='绌洪毦娆℃暟 vs 骞翠唤',
                plot_width=1000,
                legend=False,
                xlabel='骞翠唤',
                ylabel='绌洪毦娆℃暟')
        p.xaxis.major_label_orientation = pi / 2
        output_file('crashes_year.html')
        show(p)
Пример #24
0
def fnCreate_Chart_Bar1(df,strS):   
    pd.options.html.border=1 
    label1=CatAttr(columns=['Airline'], sort=False)
    plot = Bar(df, label=label1, values='Ticket Price',group='Airline', title="Average of Ticket Price- Airline wise"  + strS, legend=False,  bar_width=100, xlabel='Airlines',ylabel='Average Ticket Price')
    plot.logo=None
    script, div = components(plot,CDN)    
    return script, div 
Пример #25
0
    def mount_bar_grap(self):
        bar = Bar(self.data,
                  values='frequência',
                  label='Palavras',
                  title=self.page)

        return file_html(bar, CDN)
Пример #26
0
def systemEvolutionBarPlot(df, yLabel, values):
    with Timer(key='systemEvolutionBarPlot', verbose=True):
        p = Bar(df, label='snapshot', values=values, agg='sum', stack='software',
            legend='bottom_left', bar_width=0.5, xlabel="Snapshots", ylabel=yLabel, responsive=True, height=200,tools='hover')

        glyph_renderers = p.select(GlyphRenderer)
        bar_source = [glyph_renderers[i].data_source for i in range(len(glyph_renderers))]
        hover = p.select(HoverTool)
        hover.tooltips = [
            ('software',' @software'),
            ('value', '@height'),
        ]
        p.xaxis.formatter=FuncTickFormatter.from_py_func(getWeekStringTick)
        p.axis.minor_tick_line_color = None

        p.background_fill_color = "#fafafa"
        p.legend.location = "top_left"
        p.toolbar.logo = None
        p.toolbar_location = None

        legend=p.legend[0].legends
        p.legend[0].legends=[]
        l = Legend( location=(0, -30))
        l.items=legend
        p.add_layout(l, 'right')

        return p
Пример #27
0
def test_database():
    mongo_helper = MongoDBHelper('yelp')
    five_star_reviews = mongo_helper.reviews.query().filter(
        stars=5).count().execute().get()

    four_star_reviews = mongo_helper.reviews.query().filter(
        stars=4).count().execute().get()

    three_star_reviews = mongo_helper.reviews.query().filter(
        stars=3).count().execute().get()

    two_star_reviews = mongo_helper.reviews.query().filter(
        stars=2).count().execute().get()

    one_star_reviews = mongo_helper.reviews.query().filter(
        stars=1).count().execute().get()

    xyvalues = OrderedDict()
    xyvalues["xy"] = [
        one_star_reviews, two_star_reviews, three_star_reviews,
        four_star_reviews, five_star_reviews
    ]
    x_labels = ["1 star", "2 star", "3 star", "4 star", "5 star"]

    bar = Bar(xyvalues,
              x_labels,
              title="Review Stars",
              xlabel="Stars",
              ylabel="Review")

    output_file("reviews.html")

    show(bar)
Пример #28
0
    def calculate_average_accuracy(self, confusion_matrix):
        if confusion_matrix is None:
            return None

        scores = []
        n = np.shape(confusion_matrix)[0]
        mean_acc = 0
        for index, r in enumerate(confusion_matrix):
            ss = sum(r)
            if ss != 0:
                scores.append(float(r[index]) / ss)

        scores = np.hstack((scores, np.mean(scores)))
        class_labels = self.class_labels[:]
        class_labels.append('average')
        data = {"accuracy": scores}
        s = Bar(data,
                cat=class_labels,
                title="Per Class Accuracy",
                xlabel='categories',
                ylabel='accuracy',
                width=500,
                height=500,
                tools="pan,resize,box_zoom,hover,save,reset",
                stacked=True,
                palette=["#ec5d5e"])

        hover = s.select(dict(type=HoverTool))
        hover.tooltips = OrderedDict([
            ('accuracy', '@accuracy'),
        ])

        p = hplot(s)
        script, div = components(p)
        return (script, div)
Пример #29
0
def feature():

    # House Price Vs #Bedroom
    p1 = figure(width=550, height=500,background_fill='#e9e0db')
    p1.circle(ri.df_final['Beds'], ri.df_final['Housing_price'], fill_color="#cc6633",line_color = "#cc6633",size = 20,alpha = 0.5)
    p1.title = "House Price Vs #Bedroom"
    p1.grid.grid_line_alpha=0
    p1.xaxis.axis_label = 'Number of Bedrooms'
    p1.yaxis.axis_label = 'House Price Per SQFT'
    p1.ygrid.band_fill_color="olive"
    p1.ygrid.band_fill_alpha = 0.1
    script1, div1 = components(p1)

    
    defaults.width = 550
    defaults.height = 500
    p2 = Bar(ri.df_final,label = 'Beds',values = 'Housing_price',agg= 'mean')   
    script2, div2 = components(p2)


    # House Price Vs #Bathroom
    p3 = figure(width=550, height=500,background_fill='#e9e0db')
    p3.circle(ri.df_final['Baths'], ri.df_final['Housing_price'], fill_color="#cc6633",line_color = "#cc6633",\
            size = 20,alpha = 0.5)
    p3.title = "House Price Vs #Bedroom"
    p3.grid.grid_line_alpha=0
    p3.xaxis.axis_label = 'Number of Bathrooms'
    p3.yaxis.axis_label = 'House Price Per SQFT'
    p3.ygrid.band_fill_color="olive"
    p3.ygrid.band_fill_alpha = 0.1
    script3, div3 = components(p3)

    p4 = Bar(ri.df_final,label = 'Baths',values = 'Housing_price',agg= 'mean')   
    script4, div4 = components(p4)


    p5 = Bar(ri.df_final,label = 'Beds',values = 'Beds',agg= 'count')   
    script5, div5 = components(p5)


    p6 = Bar(ri.df_final,label = 'Baths',values = 'Baths',agg= 'count')   
    script6, div6 = components(p6)


    return render_template('FeaturePlots.html',script1= script1, div1=div1,script2=script2,div2=div2,\
                            script3=script3,div3=div3,script4=script4,div4=div4,script5=script5,div5=div5,\
                            script6=script6,div6=div6)
Пример #30
0
def graph():     
    """GENERATE TWEETS
    """
    my_list = onlinetweetsappv9.vars["regions_selected"]
          
    all_tweets = []  # Has to be here, not in app_functions.
       
    def generate_1_tweet(my_list):
        """Uses tweet generator from my app_functions module
        to append 1 tweet to all_tweets.
        """
        for tweet in app_functions.tweet_generator(my_list): # returns 1st tweet
            return all_tweets.append(tweet)        
        
    def generate_x_tweets(my_list):
        """ Generates a desired number of tweets.
        I.e. Runs the tweet generator x-times.
        """ 
        NUMBER_OF_TWEETS = 3 
        count = NUMBER_OF_TWEETS
        while count > 0:
           generate_1_tweet(my_list)
           count = count - 1
    
    def main_function(my_list):
        data = {}
        for each in my_list:
            if each == "WestUSA":
                generate_x_tweets(each)
                li = app_functions.count_matches(all_tweets)
                data.update({"WestUSA":li})
            elif each == "EastUSA":
                generate_x_tweets(each)
                li = app_functions.count_matches(all_tweets)
                data.update({"EastUSA":li})
            elif each == "Canada":
                generate_x_tweets(each)
                li = app_functions.count_matches(all_tweets)
                data.update({"Canada":li})
        return data
    
    
    """MAKE GRAPH
    """
    data = main_function(my_list)    
    df = pd.DataFrame(data.items(), columns=["region", "count"])
    plot = Bar(df, "region", values="count", title="Selected Regions")
    
    
    """RENDER TEMPLATE
    """
    script, div = components(plot, CDN)
    g = all_tweets
    
    pre_choice = onlinetweetsappv9.vars["regions_selected"]
    pr_choice = [str(x) for x in pre_choice]
    choice = " & ".join(str(x) for x in pr_choice)    
    
    return render_template("graph.html", graph=g, choice=choice, script=script, div=div)