Example #1
0
def prediction(image):
    model = load_model(model_path)
    img = load_img(image, target_size=(img_height, img_width))
    img = img_to_array(img)
    prediction = model.predict_classes(img)
    x = labels
    y = list(prediction)

    output_file("plots.html")
    # displaying the image
    url = str(image)
    source = ColumnDataSource(data=dict(url=url))
    p1 = Figure(x_range=(0, 1),
                y_range=(0, 1),
                plot_width=600,
                plot_height=400)
    p1.image_url(url='url', x=0, y=1, h=1, w=1, source=source)

    # plotting the barplot
    source = ColumnDataSource(data=dict(x=x, y=y, color=Spectral6))
    p2 = Figure(x_range=labels,
                y_range=(0, 1),
                plot_height=400,
                plot_width=600,
                title="Class Probabilites")
    p2.vbar(x='x', y='y', width=0.9, color='color', legend='x', source=source)

    # layout
    grid = gridplot([[p1, p2]])
    show(grid)
Example #2
0
def plot1():
    # copy/pasted from Bokeh Getting Started Guide - used as an example
    grouped = autompg.groupby("yr")
    mpg = grouped.mpg
    avg, std = mpg.mean(), mpg.std()
    years = list(grouped.groups)
    american = autompg[autompg["origin"] == 1]
    japanese = autompg[autompg["origin"] == 3]

    p = Figure(title="MPG by Year (Japan and US)")

    p.vbar(x=years,
           bottom=avg - std,
           top=avg + std,
           width=0.8,
           fill_alpha=0.2,
           line_color=None,
           legend="MPG 1 stddev")

    p.circle(x=japanese["yr"],
             y=japanese["mpg"],
             size=10,
             alpha=0.5,
             color="red",
             legend="Japanese")

    p.triangle(x=american["yr"],
               y=american["mpg"],
               size=10,
               alpha=0.3,
               color="blue",
               legend="American")

    p.legend.location = "top_left"
    return json.dumps(json_item(p, "myplot"))
Example #3
0
def add_volume_bars(price: pd.DataFrame, p: Figure) -> Figure:
    # note that we set the y-range here to be 3 times the data range so that the volume bars appear in the bottom third
    p.extra_y_ranges = {"vol": Range1d(start=price.Volume.min(), end=price.Volume.max()*3)}
    # use bottom=price.Volume.min() to have bottom of bars clipped off.
    p.vbar(price.Date, w, top=price.Volume, y_range_name="vol")
    # https://bokeh.pydata.org/en/latest/docs/reference/models/formatters.html#bokeh.models.formatters.NumeralTickFormatter
    p.add_layout(LinearAxis(y_range_name="vol", formatter=NumeralTickFormatter(format='$0,0')), 'right')
    return p
Example #4
0
def prediction():
    img_path = os.path.join(os.getcwd(), 'upload_folder', os.listdir('upload_folder')[0])
    model_path = os.path.join('models', 'plant_disease.model')
    binarizer_path = os.path.join('models', 'plant_disease.pickle')

    # reading only the first image from the upload_folder
    image = cv2.imread(img_path) 
    output = image.copy()
    
    # pre-process the image for classification
    image = cv2.resize(image, (80, 80))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    # load the trained convolutional neural network and the label
    # binarizer
    print("[INFO] loading network...")
    model = load_model(model_path)
    lb = pickle.loads(open(binarizer_path, "rb").read())

    # classify the input image
    print("[INFO] classifying image...")
    proba = model.predict(image)[0]
    idx = np.argmax(proba)
    label = lb.classes_[idx]
    probability = str(np.max(proba))

    # show the output image
    classes = lb.classes_
    source = ColumnDataSource(data=dict(classes=classes, probability=proba, color=Spectral6))

    plot_height = 600
    plot_width = 800
    color_mapper = None

    # barplot
    p = Figure(x_range=classes, y_range=(0,1), plot_height=plot_height, plot_width=plot_width, title="Class Probabilites")
    p.vbar(x='classes', top='probability', width=0.9, source=source)
    p.xgrid.grid_line_color = None
    p.xaxis.major_label_orientation = "vertical"
    p.xaxis.major_label_text_font_style = "italic"
    p.xaxis.major_label_text_font_size = "12pt"
    p.yaxis.major_label_text_font_size = "12pt"

    # image
    p1 = figure(x_range=(0,1), y_range=(0,1))
    print(img_path)
    p1.image_url(url=[img_path], x=0, y=1, h=1, w=1)
    
    # plotting it altogether
    show(column(p1, p))
# prediction()
Example #5
0
def multi_plot(figure_info, source):

    fig = Figure(plot_width=figure_info["plot_width"],
                 plot_height=figure_info["plot_height"],
                 title=figure_info["title"],
                 x_axis_type="datetime")

    fig.extra_y_ranges = {
        "foo": Range1d(start=0, end=figure_info["max_unemployment"])
    }
    fig.add_layout(LinearAxis(y_range_name="foo"), 'right')

    for idx in range(1, len(figure_info["names"])):
        legend_name = str(figure_info["legends"][idx - 1]) + " "

        if "Unem" not in figure_info["names"][idx]:

            fig.vbar(source=source,
                     x=figure_info["names"][0],
                     top=figure_info["names"][idx],
                     bottom=0,
                     width=1000000000,
                     color=figure_info["colors"][idx - 1],
                     fill_alpha=0.2,
                     line_alpha=0.1,
                     legend=legend_name)

        else:

            fig.line(source=source,
                     x=figure_info["names"][0],
                     y=figure_info["names"][idx],
                     line_width=figure_info["line_widths"][idx - 1],
                     alpha=figure_info["alphas"][idx - 1],
                     color=figure_info["colors"][idx - 1],
                     legend=legend_name,
                     y_range_name="foo")

    fig.legend.location = figure_info["legend_location"]
    fig.xaxis.axis_label = figure_info["xaxis_label"]
    fig.yaxis.axis_label = figure_info["yaxis_label"]
    fig.title.align = figure_info["title_align"]

    return fig
Example #6
0
def bar_viz(
    df: pd.DataFrame,
    total_grps: int,
    miss_pct: float,
    col: str,
    yscale: str,
    plot_width: int,
    plot_height: int,
    show_yticks: bool,
) -> Figure:
    """
    Render a bar chart
    """
    # pylint: disable=too-many-arguments
    title = f"{col} ({miss_pct}% missing)" if miss_pct > 0 else f"{col}"
    tooltips = [(f"{col}", "@col"), ("Count", "@cnt"),
                ("Percent", "@pct{0.2f}%")]
    if show_yticks:
        if len(df) > 10:
            plot_width = 28 * len(df)
    fig = Figure(
        x_range=list(df["col"]),
        title=title,
        plot_width=plot_width,
        plot_height=plot_height,
        y_axis_type=yscale,
        tools="hover",
        toolbar_location=None,
        tooltips=tooltips,
    )
    fig.vbar(x="col", width=0.9, top="cnt", bottom=0.01, source=df)
    tweak_figure(fig, "bar", show_yticks)
    fig.yaxis.axis_label = "Count"
    if total_grps > len(df):
        fig.xaxis.axis_label = f"Top {len(df)} of {total_grps} {col}"
        fig.xaxis.axis_label_standoff = 0
    if show_yticks and yscale == "linear":
        _format_axis(fig, 0, df["cnt"].max(), "y")
    return fig
def createPlots():
    ######################################## BS Pressure Plot ########################################
    sourceBuySell, sourceVolume = requestHoseData()
    pBuySell = Figure(plot_width=PLOT_WIDTH, plot_height=BUYSELL_PLOT_HEIGHT, name="pltBuySell")
    pBuySell.xaxis.ticker = [8.75, 9, 9.5, 10, 10.5, 11, 11.5, 13, 13.5, 14, 14.5, 14.75]
    pBuySell.xaxis.major_label_overrides = {
        8.5: "8:30", 8.75: "8:45", 9: "9:00", 9.5: "9:30", 10: "10:00",
        10.5: "10:30", 11: "11:00", 11.5: "11:30", 13: "13:00",
        13.5: "13:30", 14: "14:00", 14.5: "14:30", 14.75: "14:45"}
    pBuySell.line(x='index', y='buyPressure', source=sourceBuySell, color='green',
                  legend_label="Tổng đặt mua", name="glyphSellPressure")
    pBuySell.line(x='index', y='sellPressure', source=sourceBuySell, color='red',
                  legend_label="Tổng đặt bán", name="glyphBuyPressure")
    wz = WheelZoomTool(dimensions="width"); pBuySell.add_tools(wz); pBuySell.toolbar.active_scroll = wz
    pBuySell.toolbar.logo = None
    pBuySell.axis[0].visible = False
    pBuySell.legend.location = "top_left"
    pBuySell.legend.click_policy = "hide"
    pBuySell.legend.background_fill_alpha = 0.0

    ######################################## Volume Plot ########################################
    pVolume = Figure(width=PLOT_WIDTH, height=VOLUME_PLOT_HEIGHT, tools="pan, reset",
                     name="pltVolume")
    pVolume.toolbar.logo = None
    wz = WheelZoomTool(dimensions="height"); pVolume.add_tools(wz); pVolume.toolbar.active_scroll = wz
    pVolume.vbar(x='index', top='totalValue', width=1 /60, color='blue',
           source=sourceVolume, fill_alpha=LIQUIDITY_ALPHA, line_alpha=LIQUIDITY_ALPHA,
                 name="glyphTotalValue", legend_label="Thanh khoản toàn tt")
    pVolume.vbar(x='index', top='nnBuy', width=1/1.2/60, color='green', source=sourceVolume
           ,name="glyphNNBuy",  legend_label="NN mua",)
    pVolume.vbar(x='index', top='nnSell', width=1/1.2/60, color='red', source=sourceVolume
           ,name="glyphNNSell", legend_label="NN bán",)
    pVolume.x_range  = pBuySell.x_range
    pVolume.y_range=Range1d(-10, 45)
    pVolume.legend.location = "top_left"
    pVolume.legend.click_policy = "hide"
    pVolume.legend.background_fill_alpha = 0.0

    ######################################### OHLC plot #########################################
    orders, source, pressure = requestPSData()
    plotOhlc = createOhlcPlot(source)
    pCandle, divCandle = hookupFigure(plotOhlc) # "divCustomJS" "pltOHLC" "glyphOHLCSegment"
    pDebug = Paragraph(text=f"""["num_ps_orders": "{len(orders['index'])}"]\n"""
                             """""",
                       width=DIV_TEXT_WIDTH, height=100, name="pDebug")

    ################################# Putting all plots together ################################
    def activation_function():
        pBuySell._document.add_periodic_callback(lambda: updateDoc(pBuySell._document), 500)
        print("Document activated !")

    return pCandle, pBuySell, pVolume, divCandle , activation_function, sourceBuySell, sourceVolume, pDebug
p.title.text_font_size = "25px"
p.xaxis[0].axis_label = 'Espèces'
if data['unite'] == 1:
    p.yaxis[0].axis_label = 'Quantités (mol)'
else:
    p.yaxis[0].axis_label = 'Masses (g)'

# Calcul longueur axe
max = max(max(quantites), max(reste))*1.2
p.y_range = Range1d(start=0, end=max)

# définition de la source
source = [ColumnDataSource(data=dict(x=data_x[i], top=data_top[i], grow = data_grow[i])) for i in range(len(especes))]

for i in range(len(especes)):
    p.vbar(x='x', top='top', width = width, bottom = bottom, color = color[i],
    source = source[i], legend_label = labels[i])

p.legend.orientation = "horizontal"
p.legend.location = "top_center"
p.legend.click_policy = "hide"
p.legend.glyph_width = 60

# création du bouton
bt = Button(label = "Lance", id = '1', button_type = "success")
btp = Button(label = "Pause", id = '2', button_type = "warning")


# fonction de callback
callback = CustomJS(args=dict(source=source, anim = anim), code="""
    
    let data = new Array(source.length)
Example #9
0
def prediction():
    img_path = os.path.join(os.getcwd(), 'upload_folder',
                            os.listdir('upload_folder')[0])
    model_path = os.path.join('models', 'plant_disease.model')
    binarizer_path = os.path.join('models', 'plant_disease.pickle')

    # reading only the first image from the upload_folder
    image = cv2.imread(img_path)
    output = image.copy()

    # pre-process the image for classification
    image = cv2.resize(image, (80, 80))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    # load the trained convolutional neural network and the label
    # binarizer
    print("[INFO] loading network...")
    model = load_model(model_path)
    lb = pickle.loads(open(binarizer_path, "rb").read())

    # classify the input image
    print("[INFO] classifying image...")
    proba = model.predict(image)[0]
    idx = np.argmax(proba)
    label = lb.classes_[idx]
    probability = str(np.max(proba))

    # show the output image
    classes = lb.classes_
    source = ColumnDataSource(
        data=dict(classes=classes, probability=proba, color=Spectral6))

    plot_height = 600
    plot_width = 800
    color_mapper = None

    # barplot
    p = Figure(x_range=classes,
               y_range=(0, 1),
               plot_height=plot_height,
               plot_width=plot_width,
               title="Class Probabilites")
    p.vbar(x='classes', top='probability', width=0.9, source=source)
    p.xgrid.grid_line_color = None
    p.xaxis.major_label_orientation = "vertical"
    p.xaxis.major_label_text_font_style = "italic"
    p.xaxis.major_label_text_font_size = "12pt"
    p.yaxis.major_label_text_font_size = "12pt"

    # image
    p1 = figure(x_range=(0, 1), y_range=(0, 1))
    print(img_path)
    p1.image_url(url=[img_path], x=0, y=1, h=1, w=1)

    # plotting it altogether
    show(column(p1, p))


# prediction()
Example #10
0
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
from sklearn import tree
from sklearn import svm
from bokeh.io import curdoc, show
from bokeh.layouts import column, row
from bokeh.plotting import ColumnDataSource, Figure
from bokeh.models.widgets import Select, TextInput
from bokeh.charts import Bar

#output_file("color_change.html")

p = Figure(tools="", toolbar_location=None)
#p.vbar(x='values', top='names',width=0.5, bottom=0,source=source)
source = ColumnDataSource(data=dict(bins=[0, 1, 2, 3], counts=[1, 10, 20, 30]))
p.vbar(x = 'bins', bottom= 1, width=0.5, top='counts' , source=source)


#kernels = ["linear","rbf","poly"]
#select = Select(title="Select the kernel", value="linear", options=kernels)

input = TextInput(title="Percentage of testing set", value="0.25")

#def update_color(attrname, old, new):
#    r.glyph.fill_color = select.value
#select.on_change('value', update_color)

def update_points(attrname, old, new):
    N = float(input.value)

    iris = datasets.load_iris()
Example #11
0
def bar_viz(
    df: List[pd.DataFrame],
    ttl_grps: int,
    nrows: List[int],
    col: str,
    yscale: str,
    plot_width: int,
    plot_height: int,
    show_yticks: bool,
    orig: List[str],
    df_labels: List[str],
    baseline: int,
) -> Figure:
    """
    Render a bar chart
    """
    # pylint: disable=too-many-arguments, too-many-locals
    if len(df) > 1:
        for i, _ in enumerate(df):
            df[i] = df[i].reindex(index=df[baseline].index,
                                  fill_value=0).to_frame()

    tooltips = [
        (col, "@index"),
        ("Count", f"@{{{col}}}"),
        ("Percent", "@pct{0.2f}%"),
        ("Source", "@orig"),
    ]

    if show_yticks:
        if len(df[baseline]) > 10:
            plot_width = 28 * len(df[baseline])
    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        title=col,
        toolbar_location=None,
        tooltips=tooltips,
        tools="hover",
        x_range=list(df[baseline].index),
        y_axis_type=yscale,
    )

    offset = np.linspace(-0.08 * len(df), 0.08 *
                         len(df), len(df)) if len(df) > 1 else [0]
    for i, (nrow, data) in enumerate(zip(nrows, df)):
        data["pct"] = data[col] / nrow * 100
        data.index = [str(val) for val in data.index]
        data["orig"] = orig[i]

        fig.vbar(
            x=dodge("index", offset[i], range=fig.x_range),
            width=0.6 / len(df),
            top=col,
            bottom=0.01,
            source=data,
            fill_color=CATEGORY10[i],
            line_color=CATEGORY10[i],
        )
    tweak_figure(fig, "bar", show_yticks)

    fig.yaxis.axis_label = "Count"

    x_axis_label = ""
    if ttl_grps > len(df[baseline]):
        x_axis_label += f"Top {len(df[baseline])} of {ttl_grps} {col}"

    if orig != df_labels:
        if x_axis_label:
            x_axis_label += f", this vairable is only in {','.join(orig)}"
        else:
            x_axis_label += f"This vairable is only in {','.join(orig)}"

    fig.xaxis.axis_label = x_axis_label
    fig.xaxis.axis_label_standoff = 0

    if show_yticks and yscale == "linear":
        _format_axis(fig, 0, df[baseline].max(), "y")
    return fig
Example #12
0
import cauldron as cd
from bokeh.plotting import Figure

models = sorted(cd.shared.models, key=lambda md: md.rmse)

figure = Figure()
figure.vbar(
    x=list(range(len(models))),
    top=[md.rmse for md in models],
    width=0.6
)

figure.xaxis.axis_label = 'ARIMA Order (p, d, q)'

figure.yaxis.axis_label = 'Model Fit RMSE'

cd.display.bokeh(figure)
Example #13
0
def run(stock):
    # Get stock
    quote = get(stock, "quote")
    stock_quote = {
        "companyName": quote['companyName'],
        "latestPrice": quote['latestPrice'],
        "symbol": quote['symbol'],
        "change": "{0:.2%}".format(quote['changePercent']),
        "volume": "{:,}".format(quote['latestVolume']),
        "logo": get(stock, 'logo')['url']
    }

    # Get stock related news
    news = get(stock, "news/last/5")
    stock_news = []
    for article in news:
        stock_news.append({
            "headline": article['headline'],
            "url": article['url']
        })

    # Get stock related company data
    company = get(stock, "company")
    company_data = {
        "website": company['website'],
        "CEO": company['CEO'],
        "description": company['description']
    }

    # Get stock key stats
    stats = get(stock, "stats")
    key_stats = {
        "latestEPS": stats['latestEPS'],
        "day5Change": "{0:.2%}".format(stats['day5ChangePercent']),
        "month3Change": "{0:.2%}".format(stats['month3ChangePercent']),
        "year1Change": "{0:.2%}".format(stats['year1ChangePercent']),
    }

    # Get chart stats and make bokeh
    chart = get(stock, "chart/5y")
    chart_cds_df = get(stock, 'chart/1m')
    chart = pd.DataFrame(chart)
    chart = chart.set_index(pd.to_datetime(chart.date))

    chart_cds = ColumnDataSource(chart)

    p = Figure(x_axis_label="Date",
               y_axis_label="Price",
               x_axis_type="datetime",
               title="{} - 5Y Graph".format(stock),
               sizing_mode='scale_width')
    # p.background_fill_color = '#8FBC8F'
    # p.background_fill_alpha = 0.2
    p.grid.grid_line_alpha = 0.3

    p.line(x='date',
           y='close',
           source=chart_cds,
           line_width=1,
           color='#F2583E')

    hover = HoverTool(mode='vline')
    hover.tooltips = [('Date', '@label'), ('Open', '$@open{%0.2f}'),
                      ('High', '$@high{%0.2f}'), ('Low', '$@low{%0.2f}'),
                      ('Close', '$@close{%0.2f}')]
    hover.formatters = {
        'open': 'printf',
        'high': 'printf',
        'low': 'printf',
        'close': 'printf'
    }
    p.add_tools(hover)

    cdl = Figure(x_axis_label="Date",
                 y_axis_label="Price",
                 x_axis_type="datetime",
                 title="{} - Candlestick".format(stock),
                 sizing_mode='scale_width')

    chart_cds_df = pd.DataFrame(chart_cds_df)
    chart_cds_df = chart_cds_df.set_index(pd.to_datetime(chart_cds_df.date))

    inc = chart_cds_df.close > chart_cds_df.open
    dec = chart_cds_df.open > chart_cds_df.close
    w = 12 * 60 * 60 * 1000

    cdl.segment(chart_cds_df.index,
                chart_cds_df.high,
                chart_cds_df.index,
                chart_cds_df.low,
                color='black')
    cdl.vbar(chart_cds_df.index[inc],
             w,
             chart_cds_df.open[inc],
             chart_cds_df.close[inc],
             fill_color='#D5E1DD',
             line_color='black')
    cdl.vbar(chart_cds_df.index[dec],
             w,
             chart_cds_df.open[dec],
             chart_cds_df.close[dec],
             fill_color='#F2583E',
             line_color='black')

    cdl.grid.grid_line_alpha = 0.3

    cdl_s, cdl_div = components(cdl)

    script, div = components(p)

    return {
        "stock_quote": stock_quote,
        "stock_news": stock_news,
        "company_data": company_data,
        "key_stats": key_stats,
        "chart_script": script,
        "chart_div": div,
        "s": cdl_s,
        "d": cdl_div
    }
                        inplace=True)

            #if thresh_type == 'UDFCD':
            #    da.drop(da[da['rolling'] < udfcd_thresh[str(roll_win)]].index, inplace=True)

            if make_plot == 'true':
                print 'Add data to bokeh plot...'
                ### add some renderers
                ### Add a transparent bar for each rainfall exceedence instance
                #if max_win == '120':
                if roll_win <= 120:
                    if alarm_type == 'static_alarms':
                        p1.vbar(x=da['date'],
                                width=datetime.timedelta(minutes=int(pbin)),
                                bottom=0,
                                top=(max_Q),
                                color="green",
                                legend=str(roll_win) + '-min Static Alert',
                                line_alpha=0,
                                alpha=0.08)  #da['rolling'
                    if alarm_type == 'sat_alarms':
                        p1.vbar(x=da['date'],
                                width=datetime.timedelta(minutes=int(pbin)),
                                bottom=0,
                                top=(max_Q / 2),
                                color="green",
                                legend=str(roll_win) + '-min Static Alert',
                                line_alpha=0,
                                alpha=0.08)  #da['rolling'
                        if roll_win > 10:
                            p1.vbar(
                                x=ds['date'],
Example #15
0
def plot_bollinger_signals(data, signals, ticker=None, notebook=False):
    # create a new plot with a title and axis labels
    p = Figure(title=ticker + ' Bollinger Bands Strategy',
               x_axis_label='Date',
               x_axis_type='datetime',
               y_axis_label='Price in $',
               plot_height=500,
               plot_width=950,
               tools=['pan', 'wheel_zoom'],
               toolbar_location='below')

    inc = data['Close'] > data['Open']
    dec = data['Open'] > data['Close']
    w = 12 * 60 * 60 * 1000  # half day in ms

    p.segment(data.index, data['High'], data.index, data['Low'], color="black")
    p.vbar(data.index[inc],
           w,
           data['Open'][inc],
           data['Close'][inc],
           fill_color="#D5E1DD",
           line_color="black")
    p.vbar(data.index[dec],
           w,
           data['Open'][dec],
           data['Close'][dec],
           fill_color="#F2583E",
           line_color="black")

    # configure so that Bokeh chooses what (if any) scroll tool is active
    p.toolbar.active_scroll = "auto"

    # add a line renderer with legend and line thickness
    p.line(signals.index,
           signals['mediumband'],
           line_width=2,
           legend='Mediumband',
           line_color='black')
    p.line(signals.index,
           signals['upperband'],
           line_width=2,
           legend='Upperband',
           line_color='orange')
    p.line(signals.index,
           signals['lowerband'],
           line_width=2,
           legend='Lowerband',
           line_color='blue')

    p.triangle(signals.loc[signals.positions == 1.0].index,
               signals.lowerband[signals.positions == 1.0],
               size=15,
               fill_color='green',
               legend='Buy')
    p.inverted_triangle(signals.loc[signals.positions == -1.0].index,
                        signals.upperband[signals.positions == -1.0],
                        size=15,
                        fill_color='red',
                        legend='Sell')

    p.legend.location = "top_left"
    p.legend.click_policy = "hide"

    if notebook:
        # show the results
        show(p, notebook_handle=True)
        push_notebook()
    else:
        # output the results
        output_file('%s Bollinger Bands Strategy.html' % ticker)
        save(p)
# dessin
p = Figure(title="graph bar",
           x_range=data_x,
           y_range=(0, 100),
           plot_height=400,
           toolbar_location=None)
p.title.text_font_size = "25px"
p.yaxis[0].axis_label = 'Quantité'
p.xaxis[0].axis_label = 'Espèces'

p.y_range = Range1d(start=0, end=100)

p.vbar(x='x',
       top='top',
       width=width,
       bottom=bottom,
       color='color',
       source=source,
       legend_field='x')
p.legend.orientation = "horizontal"
p.legend.location = "top_center"

# création du bouton
bt = Button(label="Lance", button_type="success")

# fonction de callback
callback = CustomJS(args=dict(source=source, anim=anim),
                    code="""
    
    var data = new Array(source.length)
    var x = new Array(source.length)
Example #17
0
def custom_reports(report_id):

    if report_id == 'A':

        # result = db_session.execute('''select ga_date,sum(page_views),floor(dbms_random.value(2000, 6000)) as sales
        #                                from ga_sink
        #                                group by ga_date''' ).fetchall()

        result = db_session.execute(
            '''select T1.ga_date,T1.page_views, T2.total_sale
                                       from (select ga_date,sum(page_views) as page_views from ga_sink group by ga_date) T1
                                       join (select sale_date,sum(amount) as total_sale from demo_sales group by sale_date) T2
                                       on T1.ga_date=T2.sale_date''').fetchall(
            )

        # result = db_session.execute('''select T1."date",T1.page_views, T2.total_sale
        #                                from (select "date",sum(page_views) as page_views from test group by "date") T1
        #                                join (select sale_date,sum(amount) as total_sale from demo_sales group by sale_date) T2
        #                                on T1."date"=T2.sale_date''' ).fetchall()
        print(result)

        test = pd.DataFrame(result,
                            columns=['date', 'page_views', 'total_sale'])
        test['date'] = pd.to_datetime(test['date'])
        test.set_index(keys=['date'], inplace=True)
        test.sort_index(inplace=True)

        cds = ColumnDataSource(test)

        p = Figure(plot_width=1000,
                   plot_height=500,
                   title="Sales Vs Views",
                   y_range=Range1d(start=2500, end=33000),
                   x_axis_type='datetime',
                   x_axis_label='Date',
                   y_axis_label='Revenue($)')
        l1 = p.line('date',
                    'page_views',
                    source=cds,
                    line_color=d3['Category10'][10][0],
                    line_width=5,
                    legend="Page Views")
        l2 = p.line('date',
                    'total_sale',
                    source=cds,
                    line_color=d3['Category10'][10][1],
                    line_width=5,
                    legend="Revenue")
        p.extra_y_ranges = {"foo": Range1d(start=0, end=6000)}
        p.add_layout(
            LinearAxis(y_range_name='foo', axis_label="Number of Views"),
            'right')
        p.legend.location = "bottom_right"
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        p.border_fill_color = "#F8F8FF"

        p.add_tools(
            HoverTool(
                renderers=[l1],
                tooltips=[
                    ('date',
                     '@date{%F}'),  # use @{ } for field names with spaces
                    ('views', '@page_views'),
                ],
                formatters={
                    'date':
                    'datetime',  # use 'datetime' formatter for 'date' field
                    # use default 'numeral' formatter for other fields
                },

                # display a tooltip whenever the cursor is vertically in line with a glyph
                mode='vline'))

        p.add_tools(
            HoverTool(
                renderers=[l2],
                tooltips=[
                    # ( 'date',   '@date{%F}'            ),
                    ('revenue', '$@{total_sale}'
                     ),  # use @{ } for field names with spaces
                ],
                formatters={
                    # 'date'      : 'datetime', # use 'datetime' formatter for 'date' field
                    'revenue':
                    'printf',  # use 'printf' formatter for 'adj close' field
                    # use default 'numeral' formatter for other fields
                },

                # display a tooltip whenever the cursor is vertically in line with a glyph
                mode='vline'))

        return json.dumps(json_item(p))

    if report_id == "B":
        result = db_session.execute(
            '''select product_id,sum(page_views) as views
                                       from ga_sink
                                       group by product_id
                                       order by views desc ''').fetchall()

        # result = db_session.execute('''select product_id,sum(page_views) as views
        #                                from test
        #                                group by product_id
        #                                order by views desc ''' ).fetchall()

        test = pd.DataFrame(result, columns=['product_id', 'page_views'])
        test.set_index(keys=['product_id'], inplace=True)

        cds = ColumnDataSource(test)

        p = Figure(x_range=cds.data['product_id'],
                   plot_height=350,
                   title="Top Products by Views",
                   tools="")

        p.vbar(x='product_id',
               top='page_views',
               source=cds,
               width=0.9,
               fill_color=factor_cmap(field_name='product_id',
                                      palette=d3['Category10'][10],
                                      factors=cds.data['product_id']))
        p.xgrid.grid_line_color = None
        p.y_range.start = 0
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        p.border_fill_color = "#F8F8FF"

        return json.dumps(json_item(p))
    if report_id == "C":
        # cdata= [{'product_id':'BGB-US-001','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-002','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-003','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-004','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-005','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-006','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-007','total_sale': random.randint(1000,8000)}]

        cdata = db_session.execute('''select product_id,sum(amount)
                                     from demo_sales
                                     group by product_id''').fetchall()
        c = pd.DataFrame(cdata, columns=['product_id', 'amount'])
        c.rename(columns={"amount": "total_sale"}, inplace=True)
        print(c)
        c.set_index(keys=['product_id'], inplace=True)
        c['angle'] = c['total_sale'] / c['total_sale'].sum() * 2 * pi
        c['color'] = d3['Category10'][10][len(c) - 1::-1]
        c['percent'] = round(c['total_sale'] / c['total_sale'].sum() * 100, 0)

        cds = ColumnDataSource(c)

        p = Figure(plot_height=350,
                   title="Revenue Breakdown by Product",
                   tools="hover",
                   tooltips="@product_id: @percent %",
                   x_range=(-0.5, 1.0))

        p.wedge(x=0,
                y=1,
                radius=0.4,
                start_angle=cumsum('angle', include_zero=True),
                end_angle=cumsum('angle'),
                line_color="white",
                fill_color='color',
                legend='product_id',
                source=cds)

        p.axis.axis_label = None
        p.axis.visible = False
        p.grid.grid_line_color = None
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        p.border_fill_color = "#F8F8FF"

        return json.dumps(json_item(p))
                    inplace=True)

        print 'Creating precip bokeh plot...'

        ### add some renderers
        #p=Area(df, legend="top_right")
        #glyph = VBar(x='date', top='top', bottom=0, width = 5.5, fill_color="firebrick")
        #p.add_glyph(ColumnDataSource(dict(date=df['date'],top=df['precip'])), glyph)

        ### Add a transparent bar for each rainfall exceedence instance
        if max_win == '120':
            if roll_win <= 120:
                p1.vbar(x=da['date'],
                        width=datetime.timedelta(minutes=int(pbin)),
                        bottom=0,
                        top=10,
                        color="green",
                        line_alpha=0,
                        alpha=0.08)  #da['rolling'
        if max_win == '360':
            if roll_win > 120 and roll_win <= 360:
                p1.vbar(x=da['date'],
                        width=datetime.timedelta(minutes=int(pbin)),
                        bottom=0,
                        top=10,
                        color="orange",
                        line_alpha=0,
                        alpha=0.08)  #da['rolling'
        if max_win == '1440':
            if roll_win > 360 and roll_win <= 1440:
                p1.vbar(x=da['date'],
Example #19
0
class Plot2d:
    def __init__(self,
                 x_range=None,
                 y_range=None,
                 x_label="",
                 y_label="",
                 tooltip=None,
                 title="",
                 width=600,
                 height=400,
                 yscale="auto",
                 font_size="1vw",
                 hover_mode="mouse"):
        hover = HoverTool(tooltips=tooltip, mode=hover_mode)

        if y_range == None:
            self.plot = Figure(
                tools=[hover, "pan,wheel_zoom,box_zoom,reset,crosshair,tap"],
                plot_width=width,
                active_drag="box_zoom",
                plot_height=height,
                background_fill_color="white",
                x_axis_type="auto",
                y_axis_type=yscale)
        else:
            self.plot = Figure(
                tools=[hover, "pan,wheel_zoom,box_zoom,reset,crosshair,tap"],
                plot_width=width,
                active_drag="box_zoom",
                plot_height=height,
                background_fill_color="white",
                x_axis_type="auto",
                y_axis_type=yscale,
                y_range=y_range,
                x_range=x_range)

        self.plot.xaxis.axis_label = x_label
        self.plot.yaxis.axis_label = y_label

        self.plot.xaxis.major_label_text_font_size = font_size
        self.plot.yaxis.major_label_text_font_size = font_size
        self.plot.xaxis.axis_label_text_font_size = font_size
        self.plot.yaxis.axis_label_text_font_size = font_size
        self.plot.legend.label_text_font_size = font_size
        self.plot.title.text_font_size = font_size
        self.plot.title.text = title

    def vbar(self, source, y="y", x="x", line_width=0.01):
        self.plot.vbar(top=y,
                       x=x,
                       width=0.8,
                       source=source,
                       fill_color="dodgerblue",
                       line_color="black",
                       line_width=line_width,
                       alpha=0.8,
                       hover_fill_color='red',
                       hover_line_color='red',
                       hover_alpha=0.8)
        return self.plot

    def quad(self,
             source,
             top,
             bottom='bottom',
             left='left',
             right='right',
             name='data',
             line_width=0.1):
        self.plot.quad(top=top,
                       bottom=bottom,
                       left=left,
                       right=right,
                       name=name,
                       source=source,
                       fill_color="dodgerblue",
                       line_color="black",
                       line_width=line_width,
                       alpha=0.8,
                       hover_fill_color='red',
                       hover_line_color='red',
                       hover_alpha=0.8)
        return self.plot

    def line(self,
             source,
             x='x',
             y='y',
             color="black",
             line_width=1.5,
             line_alpha=0.9):
        self.plot.line(x=x,
                       y=y,
                       source=source,
                       color=color,
                       line_width=line_width,
                       line_alpha=line_alpha)
        return self

    def circle(self,
               source,
               x='x',
               y='y',
               color="blue",
               size=8,
               line_color='black',
               alpha=0.7,
               hover_color="blue",
               hover_alpha=1,
               hover_line_color='red',
               radius=0.0165,
               fill_color='lightgray',
               line_width=0.3,
               hover_fill_color=None):
        self.plot.circle(
            x=x,
            y=y,
            source=source,
            color=color,
            size=size,
            line_color=line_color,
            alpha=alpha,
            hover_color=hover_color,
            hover_alpha=hover_alpha,
            hover_line_color=hover_line_color,
            fill_color=fill_color,
            hover_fill_color=hover_fill_color,
        )
        return self

    def set_colorbar(self, z_value):
        ''' Setup for colorbar
        '''
        dz = z_value

        # removing NaN in ranges
        dz_valid = [x if x > -999 else np.nan for x in dz]
        dzmax, dzmin = np.nanmax(dz_valid), np.nanmin(dz_valid)

        if np.log10(dzmax) > 4 or np.log10(dzmin) < -3:
            ztext = ['{:4.2e}'.format(i) for i in dz_valid]
            cbarformat = "%2.1e"
        elif np.log10(dzmin) > 0:
            ztext = ['{:5.2f}'.format(i) for i in dz_valid]
            cbarformat = "%4.2f"
        else:
            ztext = ['{:6.2f}'.format(i) for i in dz_valid]
            cbarformat = "%5.2f"
        return ztext, cbarformat

    def colorbar(self, mapper, title='(Val - Ref)'):
        formatter = PrintfTickFormatter(format="%4.2f")

        color_bar = ColorBar(color_mapper=mapper,
                             label_standoff=16,
                             title=title,
                             major_label_text_font_style='bold',
                             padding=26,
                             major_label_text_align='left',
                             major_label_text_font_size="10pt",
                             formatter=formatter,
                             title_text_baseline='alphabetic',
                             location=(0, 0))
        self.plot.add_layout(color_bar, 'right')
        return self

    def wedge(self,
              source,
              field=None,
              x="x",
              y="y",
              mapper=None,
              radius=0.0165,
              colorbar_title='counts'):

        if mapper:
            self.plot = self.circle(
                source,
                y=y,
                x=x,
                radius=radius,
                fill_color={
                    'field': field,
                    'transform': mapper
                },
                line_color='black',
                line_width=0.3,
            ).circle(source,
                     y=y,
                     x=x,
                     radius=radius + 0.005,
                     fill_color=None,
                     line_color=None,
                     line_width=3,
                     hover_fill_color={
                         'field': field,
                         'transform': mapper
                     },
                     hover_line_color='red').colorbar(
                         mapper, title=colorbar_title).plot
        elif field:
            self.plot = self.circle(
                source,
                y=y,
                x=x,
                radius=radius,
                hover_fill_color='lightgrey',
                fill_color={
                    'field': 'color'
                },
                line_color='black',
                line_width=0.3,
            ).plot
        else:
            self.plot = self.circle(
                source,
                y=y,
                x=x,
                radius=radius,
                hover_fill_color='lightgrey',
                fill_color='darkgrey',
                line_color='black',
                line_width=0.3,
            ).plot

        return self

    def segment(self,
                source,
                x0='segx0',
                x1='segx1',
                y0='segy0',
                y1='segy1',
                line_width=2,
                line_color='#1e90ff'):
        seg = Segment(x0=x0,
                      x1=x1,
                      y0=y0,
                      y1=y1,
                      line_width=line_width,
                      line_color=line_color)

        self.plot.add_glyph(source, seg)

        self.plot.yaxis.ticker = FixedTicker(ticks=[0, 1])
        self.plot.yaxis.major_label_overrides = {'0': 'bad', '1': 'good'}
        return self
Example #20
0
    def _doc_factory(self, doc):
        settings = process_manager.service(ConfigObject)
        ds = process_manager.service(DataStore)

        df = ds[self.read_key]

        # calculate initial values to initialize displayed elements
        columns = df.columns
        first_col = columns[0]  # 'pl_letter' #columns[0]
        first_stats, first_hist, first_edges = self._col_stats(df[first_col])

        # set up data sources
        hist_source = ColumnDataSource(
            data=self._hist_source_dict(first_hist, first_edges)
        )
        table_source = ColumnDataSource(
            data=self._table_source_dict(first_stats)
        )

        # set up dashboard components
        plot = Figure(
            title=first_col,
            tools="xpan,xwheel_zoom,box_zoom,reset",
            active_drag="xpan",
            active_scroll="xwheel_zoom",
        )

        plot.vbar(top="top", x="x", width="width", bottom=0, source=hist_source)

        slider = Slider(
            start=1,
            end=5 * len(first_hist),
            value=len(first_hist),
            step=1,
            title="Bin Count",
        )
        slider.disabled = isinstance(first_edges[0], str)

        dropdown = Dropdown(
            label="Column",
            menu=[(col, col) for col in df.columns],
            value=df.columns[0],
        )

        table = DataTable(
            source=table_source,
            columns=[
                TableColumn(field="quantity", title="Quantity"),
                TableColumn(field="value", title="Value"),
            ],
        )

        # configure callbacks
        slider_interaction = True

        def dropdown_callback(attr, old, new):
            nonlocal df, plot, hist_source, dropdown
            nonlocal table, table_source
            nonlocal slider, slider_interaction
            stats, hist, edges = self._col_stats(df[new])
            self._update_histogram(plot, hist_source, hist, edges, new)
            self._update_table(table, table_source, stats)

            dropdown.label = new

            slider_interaction = False  # don't recalculate again
            slider.start = 1
            slider.value = len(hist)
            slider.end = 5 * len(hist)
            slider.disabled = isinstance(edges[0], str)
            slider_interaction = True  # re-enable slider

        dropdown.on_change("value", dropdown_callback)

        def slider_callback(attr, old, new):
            nonlocal df, plot, hist_source, dropdown
            nonlocal slider_interaction
            if slider_interaction:
                stats, hist, edges = self._col_stats(
                    df[dropdown.value], n_bins=new
                )
                self._update_histogram(plot, hist_source, hist, edges)

        slider.on_change("value", slider_callback)

        # Position elements in document
        root = layout(
            [[plot, widgetbox(dropdown, table)], [slider]]
        )


        doc.add_root(root)
Example #21
0
df = pd.concat([ecl, solar], axis=1)
df = df.dropna()

fv = df.Nombre

TOOLS = "hover,crosshair,pan,wheel_zoom,box_zoom,reset,box_select,lasso_select,save"
p1 = Figure(name="p1",
            tools=TOOLS,
            sizing_mode="scale_width",
            plot_width=1200,
            plot_height=450,
            x_range=FactorRange(*fv))
p1.vbar(x=fv,
        top=df.oscuridad,
        width=0.6,
        line_color='orangered',
        fill_color='orangered')
p1.xaxis.major_label_orientation = pi / 3
p1.yaxis.axis_label = "Porcentaje oscuridad"

p2 = Figure(name="p2",
            tools=TOOLS,
            plot_width=1200,
            plot_height=900,
            y_range=FactorRange(factors=list(df.Nombre)),
            sizing_mode="scale_width")  #list(data2.index)
p2.xaxis.formatter = DatetimeTickFormatter(hours=['%d/%m %H:00'], days=['%F'])

p2.hbar(y=list(df.Nombre),
        left=df.c1,
class NumDocsFigure:
    def __init__(
        self,
        min_date: date,
        max_date: date,
        date_range_widget: DateRangeWidget,
    ):
        self._min_date = min_date
        self._max_date = max_date

        self._source = ColumnDataSource(self._new_source_data())

        self._figure = Figure(
            title="# Documents per day",
            toolbar_location="above",
            tools="save",
            sizing_mode="stretch_width",
            plot_height=200,
            x_axis_type="datetime",
            y_axis_type="linear",
            x_range=(
                date_to_timestamp(self._min_date, tzinfo_=timezone.utc) * 1000,
                date_to_timestamp(self._max_date, tzinfo_=timezone.utc) * 1000,
            ),
            min_border_left=40,
        )
        self._figure.toolbar.autohide = True
        self._figure.toolbar.logo = None
        self._figure.xaxis[0].formatter = DatetimeTickFormatter(
            days=["%d %b"], months=["%b"]
        )
        self._figure.yaxis[0].formatter = NumeralTickFormatter(format="0a")
        self._figure.vbar(
            source=self._source,
            x="days",
            top="num_docs",
            width=timedelta(days=1).total_seconds() * 1000,
        )

        self._selected_annotation = BoxAnnotation(
            left=self._figure.x_range.start,
            right=self._figure.x_range.end,
            fill_color="gray",
            line_color="darkgray",
            line_alpha=1,
        )
        date_range_widget.slider.js_link(
            "value", self._selected_annotation, "left", attr_selector=0
        )
        date_range_widget.slider.js_link(
            "value", self._selected_annotation, "right", attr_selector=1
        )
        self._figure.add_layout(self._selected_annotation)

        self.figure = row(self._figure)

    @classmethod
    def _new_source_data(cls) -> Mapping[str, List[object]]:
        return {"days": [], "num_docs": []}

    @coroutine
    def display_update(self, num_docs_per_day: Sequence[int]) -> None:
        new_data = self._new_source_data()
        for day, num_docs in zip(
            date_range(self._min_date, self._max_date), num_docs_per_day
        ):
            if not num_docs:
                continue
            new_data["days"].append(date_to_datetime(day, tzinfo_=timezone.utc))
            new_data["num_docs"].append(num_docs)
        self._source.data = new_data
    Redwood_City_y=df_station.dock_count[df_station.city == "Redwood City"],
    Mountain_View_x=df_station.id[df_station.city == "Mountain View"],
    Mountain_View_y=df_station.dock_count[df_station.city == "Mountain View"],
    Palo_Alto_x=df_station.id[df_station.city == "Palo Alto"],
    Palo_Alto_y=df_station.dock_count[df_station.city == "Palo Alto"],
    San_Francisco_x=df_station.id[df_station.city == "San Francisco"],
    San_Francisco_y=df_station.dock_count[df_station.city == "San Francisco"],
))

#bar plot----------

plot = Figure(plot_width=400, plot_height=400)
#plot.vbar(x=dc_id, width=0.5, bottom=0, top=dc_dcount, color="firebrick")
plot.vbar(x='x',
          top='y',
          source=source,
          width=0.5,
          bottom=0,
          color="firebrick")

#call back ----------
# plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)


def callback1(source=source, source2=source2):
    data = source.data
    data2 = source2.data
    f = cb_obj.value
    data.x = data[f + '_x']
    data.y = data[f + '_y']
    source.change.emit()
Example #24
0
from bokeh.charts import Bar
from bokeh.io import save
from bokeh.plotting import Figure, ColumnDataSource
import pandas as pd

dict = {'values': [10, 20, 30, 40], 'names': ['TP', 'FP', 'TN', "FN"]}
df = pd.DataFrame(dict)

p = Bar(df, 'names', values='values', title="test chart")

dict1 = {'values': [10, 20, 30, 40], 'names': ['TP', 'FP', 'TN', "FN"]}
source = ColumnDataSource(dict1)

#p = Bar(df, 'names', values='values', title="test chart")
r = Figure(tools="", toolbar_location=None)
r.vbar(x='values', top='names', width=0.5, bottom=0, source=source)

save(r, 'test3.html')