示例#1
0
def Violin(dfs, measurement, configs, analysisType, **addConfigs):
    """Plots a measurement from all df as boxwisker"""
    newConfigs = addConfigs
    log.info("Generating Violin Plot for {}".format(measurement))
    try:
        plot = hv.Violin(
            dfs["All"],
            kdims="Name",
            vdims=measurement,
            label="Violin: {}".format(measurement),
            group="Violin: {}".format(measurement),
        )
        # get labels from the configs
        # ylabel = "{} [{}]".format(measurement, dfs[dfs["keys"][0]]["units"][dfs[dfs["keys"][0]]["measurements"].index(measurement)])
        try:
            ylabel = "{} [{}]".format(
                measurement,
                dfs[dfs["keys"][0]]["units"][dfs[
                    dfs["keys"][0]]["measurements"].index(measurement)],
            )
        except Exception as err:
            log.error(
                "Label could not be generated for violin plot {}. Error: {}".
                format(measurement, err))
            ylabel = "Y-Axis"
        plot.opts(
            box_alpha=0.3,
            xrotation=80,
            box_color="blue",
            height=500,
            show_legend=False,
            width=600,
            ylabel=ylabel,  # inner='quartiles'
        )

        # Update the plot specific options if need be
        generalOptions = configs[analysisType].get("General", {})
        newConfigs.update(generalOptions.copy())
        data_options = (configs[analysisType].get(measurement, {}).get(
            "Violin", {}).get("PlotOptions", {}))
        newConfigs.update(configs[analysisType].get(
            "{}Options".format("Violin"), {}))
        newConfigs.update(data_options)
        plot = customize_plot(plot, "", configs[analysisType], **newConfigs)
    except Exception as err:
        log.error(
            "Unexpected error happened during violin plot generation {}. Error: {}"
            .format(measurement, err))
        return None

    return plot
def create_dist_plot(ds, fold):
    df = ds.data
    df['absolute error'] = (df.y - df.y_pred).abs()
    df_selected = df.loc[df['data_split'] == fold].copy()
    df_selected['selected'] = fold

    df_all = df.groupby(['data_split', 'in_train_set']).mean().reset_index()
    df_all['selected'] = 'all'

    ds_dist = hv.Dataset(pd.concat([df_selected, df_all]),
                         kdims=['selected', 'in_train_set'],
                         vdims=['absolute error'])
    opts = dict(width=600, height=540)
    boxWhisker = (ds_dist.to(hv.BoxWhisker,
                             kdims=['selected', 'in_train_set'],
                             groupby=[]).opts(**opts, ylim=(0, 4)))
    violin = hv.Violin(boxWhisker).opts(**opts)
    return (boxWhisker + violin).opts(tabs=True)
示例#3
0
            print('CpG', CpG, sep='\t', file=Violin_out)
            GpC = float(columns[6])
            print('GpC', GpC, sep='\t', file=Violin_out)


violin_plot(out_file)

#==============================plot 1 = violin plot==============================

violin_data = 'arranged_data_violin.txt'

#loading the data
df = pd.read_csv(violin_data, sep='\t')
# Declearing the data
#plot
violin = hv.Violin(df, ('Dinucleotide', 'Dinucleotides'),
                   ('ratio', 'Ratio')).redim.range(ratio=(0, 2))
violin.opts(height=500,
            width=900,
            violin_fill_color=dim('Dinucleotides').str(),
            cmap='Set1')
#save plot
hv.save(violin, 'Promo_violin_plot.png', fmt='png')

#========================making the line plot with guassian filter=========================

count_CpG = {}
count_GpC = {}

with open('promoters_output.txt') as fh:
    header = fh.readline()
    for line in fh:
    def holoviews_violinPlot_large(self):
        import holoviews as hv
        from holoviews import dim
        from bokeh.sampledata.autompg import autompg
        from bokeh.layouts import row, widgetbox
        from bokeh.models import Select
        from bokeh.plotting import curdoc

        #### Bokeh Imports
        from bokeh.plotting import figure, show, output_file
        from bokeh.embed import components
        from bokeh.resources import CDN

        df_for_bokeh = pd.read_pickle("./df_holoviewPlots.pkl")
        hv.extension('bokeh')
        ### OWN EXPERI STARTS ===  businesstravel  dailyrate
        # label = "WATSON ANALYTICS EMPLOYEE ATTRITION"
        #TBD-- ##label=label

        # violin_plot ==1 ---- BUSINESS_TRAVEL..'DAILY_RATE
        violin_plot = hv.Violin(
            df_for_bokeh, ('businesstravel', 'BUSINESS_TRAVEL'),
            ('dailyrate', 'DAILY_RATE')).redim.range(dailyrate=(120, 1300))
        violin_plot.opts(height=500,
                         width=900,
                         show_legend=True,
                         violin_fill_color=dim('BUSINESS_TRAVEL').str(),
                         cmap='Set1')
        violin_plot = hv.render(violin_plot)
        print("---------type(violin_plot)--------", type(violin_plot))
        ##<class 'bokeh.plotting.figure.Figure'>
        js_violin_plot, div_violin_plot = components(violin_plot)
        cdn_js_violin_plot = CDN.js_files[0]  # NOT REQD ??
        cdn_css_violin_plot = CDN.css_files[0]  # NOT REQD ??

        # violin_plot ==2 ---- BUSINESS_TRAVEL..ATTRITTION -- attrition
        violin_plot1 = hv.Violin(
            df_for_bokeh, ('businesstravel', 'BUSINESS_TRAVEL'),
            ('attrition', 'ATTRITION')).redim.range(attrition=(0, 1))
        violin_plot1.opts(height=500,
                          width=900,
                          show_legend=True,
                          violin_fill_color=dim('BUSINESS_TRAVEL').str(),
                          cmap='Set1')
        violin_plot1 = hv.render(violin_plot1)
        print("---------type(violin_plot)--------", type(violin_plot1))
        ##<class 'bokeh.plotting.figure.Figure'>
        js_violin_plot1, div_violin_plot1 = components(violin_plot1)
        cdn_js_violin_plot1 = CDN.js_files[0]  # NOT REQD ??
        cdn_css_violin_plot1 = CDN.css_files[0]  # NOT REQD ??

        return js_violin_plot, div_violin_plot, cdn_js_violin_plot, cdn_css_violin_plot, js_violin_plot1, div_violin_plot1, cdn_js_violin_plot1, cdn_css_violin_plot1

        # def holoviews_plot_1(self):
        #     #
        #     """
        #     #Working Code - OK -- ORIGINAL -- Cars MPG Example -Not Reqd-- dc_holoviews_plotview
        #     """
        #     import holoviews as hv
        #     from bokeh.layouts import row, widgetbox
        #     from bokeh.models import Select
        #     from bokeh.plotting import curdoc
        #     from bokeh.sampledata.autompg import autompg
        #     #### Bokeh Imports
        #     from bokeh.plotting import figure, show, output_file
        #     from bokeh.embed import components
        #     from bokeh.resources import CDN

        #     df = autompg.copy()

        #     SIZES = list(range(6, 22, 3))
        #     ORIGINS = ['North America', 'Europe', 'Asia']

        #     # data cleanup
        #     df.cyl = [str(x) for x in df.cyl]
        #     df.origin = [ORIGINS[x-1] for x in df.origin]

        #     df['year'] = [str(x) for x in df.yr]
        #     del df['yr']

        #     df['mfr'] = [x.split()[0] for x in df.name]
        #     df.loc[df.mfr=='chevy', 'mfr'] = 'chevrolet'
        #     df.loc[df.mfr=='chevroelt', 'mfr'] = 'chevrolet'
        #     df.loc[df.mfr=='maxda', 'mfr'] = 'mazda'
        #     df.loc[df.mfr=='mercedes-benz', 'mfr'] = 'mercedes'
        #     df.loc[df.mfr=='toyouta', 'mfr'] = 'toyota'
        #     df.loc[df.mfr=='vokswagen', 'mfr'] = 'volkswagen'
        #     df.loc[df.mfr=='vw', 'mfr'] = 'volkswagen'
        #     del df['name']

        #     columns = sorted(df.columns)
        #     print("---------COLUMNS ==-----",columns)
        #     discrete = [x for x in columns if df[x].dtype == object]
        #     continuous = [x for x in columns if x not in discrete]
        #     quantileable = [x for x in continuous if len(df[x].unique()) > 20]
        #     print("---------quantileable----",quantileable)

        #     renderer = hv.renderer('bokeh')
        #     print("----------HOLOVIEWS -----",renderer)
        #     ##  BokehRenderer()
        #     #
        #     options = hv.Store.options(backend='bokeh')
        #     options.Points = hv.Options('plot', width=800, height=500, size_index=None,) ## OK works
        #     options.Points = hv.Options('style', cmap='rainbow', line_color='black')

        #     def create_figure():
        #         x = Select(title='X-Axis', value='mpg', options=quantileable)
        #         ## Select == /home/dhankar/anaconda2/lib/python2.7/site-packages/bokeh/models/widgets/inputs.py

        #         #x.on_change('value', update)

        #         y = Select(title='Y-Axis', value='hp', options=quantileable)
        #         #y.on_change('value', update)

        #         #size = Select(title='Size', value='None', options=['None'] + quantileable)
        #         size = Select(title='Size', value='None', options=['None'] + quantileable)
        #         #size.on_change('value', update)

        #         color = Select(title='Color', value='None', options=['None'] + quantileable)
        #         #color.on_change('value', update)

        #         label = "Plot MAIN TITLE == %s vs %s" % (x.value.title(), y.value.title())
        #         kdims = [x.value, y.value]
        #         print("---------TYPE === kdims----------",type(kdims)) ##<class 'list'>
        #         print("--------- kdims----------",kdims) ## ['mpg', 'hp']

        #         opts, style = {}, {}
        #         opts['color_index'] = color.value if color.value != 'None' else None
        #         if size.value != 'None': ## DHANKAR --- CHANGED --- != TO ==
        #             opts['size_index'] = size.value
        #             opts['scaling_factor'] = (1./df[size.value].max())*200
        #             print("-----------AAAA--opts--",opts) ## This line Doesnt print --- this Code doesnt get into this -- - if -- Statement
        #         print("-----------TYPE--opts--",type(opts)) ## <class 'dict'>
        #         print("-----------BBBB--opts--",opts) ## {'color_index': None} ## Dict value printed outside the -- if -- Statement
        #         #points = hv.Points(df, kdims=kdims, label=label).opts(plot=opts, style=style) ## Original Code
        #         #points = hv.Points(df, vdims=['mfr', 'size'] , tools=['hover'] , kdims=kdims, label=label).opts(color='mfr')
        #         """
        #         Supplied data does not contain specified dimensions, the following dimensions were not found: ['size']
        #         PandasInterface expects tabular data, for more information on supported datatypes see http://holoviews.org/user_guide/Tabular_Datasets.html
        #         """
        #         #points = hv.Points(df, vdims=['mfr'] , tools=['hover'] , kdims=kdims, label=label).opts(color='mfr')
        #         ## WARNING:param.Points01326: Setting non-parameter attribute tools=['hover'] using a mechanism intended only for parameters

        #         points = hv.Points(df, vdims=['mfr'] , kdims=kdims, label=label).opts(color='mfr')

        #         """
        #         File "pandas/_libs/hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
        #         KeyError: 'None'

        #         """

        #         # FOO--- Dhankar Code
        #         from bokeh.io import show
        #         from bokeh.models.tickers import FixedTicker

        #         from bokeh.themes import built_in_themes
        #         from bokeh.io import curdoc

        #         curdoc().theme = 'dark_minimal'

        #         bokeh_plot = hv.render(points)
        #         print("---------type(bokeh_plot)--------",type(bokeh_plot))
        #         ##<class 'bokeh.plotting.figure.Figure'>
        #         #bokeh_plot -- SHOW
        #         #show(bokeh_plot)
        #         #
        #         #hv.save(bokeh_plot, 'bokeh_plot.png')

        #         #return renderer.get_plot(points).state  ## Original Code
        #         #return renderer.get_plot(points).state , bokeh_plot  ## ERROR - we are intentionally Returning a TUPLE
        #         return bokeh_plot  #OWN EXPERI ## ERROR - we are intentionally Returing a TUPLE

        #     bokeh_plot = create_figure()

        #     js_boxplot, div_boxplot = components(bokeh_plot)
        #     cdn_js_boxplot=CDN.js_files[0] # NOT REQD ??
        #     cdn_css_boxplot=CDN.css_files[0] # NOT REQD ??

        #     return js_boxplot,div_boxplot ,cdn_js_boxplot,cdn_css_boxplot
        """
        ### Original Code BElow ----------- OK 

        def update(attr, old, new):
            layout.children[1] = create_figure()

        x = Select(title='X-Axis', value='mpg', options=quantileable)
        x.on_change('value', update)

        y = Select(title='Y-Axis', value='hp', options=quantileable)
        y.on_change('value', update)

        size = Select(title='Size', value='None', options=['None'] + quantileable)
        size.on_change('value', update)

        color = Select(title='Color', value='None', options=['None'] + quantileable)
        color.on_change('value', update)

        controls = widgetbox([x, y, color, size], width=200)
        layout = row(controls, create_figure()) ## Original Code --- Commented Out as gives ERROR - we are intentionally Returing a TUPLE 
        print("----------layout---------",layout)
        print("------TYPE----layout---------",type(layout))
        
        #----------layout--------- Row(id='1138', ...)
        #------TYPE----layout--------- <class 'bokeh.models.layouts.Row'>

        
        curdoc().add_root(layout)           ## Original Code --- Commented Out as gives ERROR - we are intentionally Returing a TUPLE 
        curdoc().title = "Crossfilter"       ## Original Code --- Commented Out as gives ERROR - we are intentionally Returing a TUPLE 
        print("---curdoc()--------------",curdoc()) ## <bokeh.document.document.Document object at 

        ### FOO_ERROR --- Some issue with -- curdoc() == https://github.com/bokeh/bokeh/issues/8020

        """
        # ---curdoc()-------------- <bokeh.document.document.Document object at 0x7f778e77f6d8>
        # WARNING:bokeh.embed.util:
        # You are generating standalone HTML/JS output, but trying to use real Python
        # callbacks (i.e. with on_change or on_event). This combination cannot work.

        # Only JavaScript callbacks may be used with standalone output. For more
        # information on JavaScript callbacks with Bokeh, see:

        #     http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html

        # Alternatively, to use real Python callbacks, a Bokeh server application may
        # be used. For more information on building and running Bokeh applications, see:

        #     http://bokeh.pydata.org/en/latest/docs/user_guide/server.html
        """
    def holoviews_violinPlot_small(self):
        """
        holoviews_violinPlot_small
        """
        try:
            #
            import holoviews as hv
            from holoviews import dim
            from bokeh.sampledata.autompg import autompg
            from bokeh.layouts import row, widgetbox
            from bokeh.models import Select, HoverTool
            #from bokeh.models import HoverTool , WheelZoomTool , LassoSelectTool ,BoxZoomTool, ResetTool , PanTool
            from bokeh.plotting import curdoc

            #### Bokeh Imports
            from bokeh.plotting import figure, show, output_file
            from bokeh.embed import components
            from bokeh.resources import CDN
            #
            df_for_bokeh = pd.read_pickle("./df_holoviewPlots.pkl")

            hv.extension('bokeh')

            ### OWN EXPERI STARTS ===  businesstravel  dailyrate
            # label = "WATSON ANALYTICS EMPLOYEE ATTRITION"
            #TBD-- ##label=label

            # violin_plot ==1 ---- BUSINESS_TRAVEL..'DAILY_RATE
            violin_plot = hv.Violin(
                df_for_bokeh, ('businesstravel', 'BUSINESS_TRAVEL'),
                ('dailyrate', 'DAILY_RATE')).redim.range(dailyrate=(120, 1300))
            violin_plot.opts(height=200,
                             width=210,
                             show_legend=False,
                             tools=['hover'],
                             violin_fill_color=dim('BUSINESS_TRAVEL').str(),
                             cmap='Set1')
            violin_plot = hv.render(violin_plot)
            #plot_width=150, plot_height=170
            print("---------type(violin_plot)--------", type(violin_plot))
            ##<class 'bokeh.plotting.figure.Figure'>
            violin_plot.toolbar.logo = None
            violin_plot.toolbar_location = None

            js_violin_plot, div_violin_plot = components(violin_plot)
            cdn_js_violin_plot = CDN.js_files[0]  # NOT REQD ??
            cdn_css_violin_plot = CDN.css_files[0]  # NOT REQD ??

            # violin_plot ==2 ---- BUSINESS_TRAVEL..ATTRITTION -- attrition
            violin_plot1 = hv.Violin(
                df_for_bokeh, ('businesstravel', 'BUSINESS_TRAVEL'),
                ('attrition', 'ATTRITION')).redim.range(attrition=(0, 1))
            violin_plot1.opts(height=200,
                              width=210,
                              show_legend=False,
                              tools=['hover'],
                              violin_fill_color=dim('BUSINESS_TRAVEL').str(),
                              cmap='Set1')
            violin_plot1 = hv.render(violin_plot1)
            print("---------type(violin_plot)--------", type(violin_plot1))
            ##<class 'bokeh.plotting.figure.Figure'>
            violin_plot1.toolbar.logo = None
            violin_plot1.toolbar_location = None

            js_violin_plot1, div_violin_plot1 = components(violin_plot1)
            cdn_js_violin_plot1 = CDN.js_files[0]  # NOT REQD ??
            cdn_css_violin_plot1 = CDN.css_files[0]  # NOT REQD ??
            return js_violin_plot, div_violin_plot, cdn_js_violin_plot, cdn_css_violin_plot, js_violin_plot1, div_violin_plot1, cdn_js_violin_plot1, cdn_css_violin_plot1

        except Exception as e:
            print(
                "--except Exception as e:---FROM ===>>-dc_holoviews.py--==--def holoviews_violinPlot_small(self)------",
                e)
            #return  >>>  ## Custom HTML to come here ...
            """
示例#6
0
def violin_sueldos(df):
    violin = hv.Violin(df, ('valor_cargo', 'Valor de Cargo'),
                       ('sueldo_basico', 'Sueldo'))
    violin.options(height=500, width=500)
    return hv.renderer('bokeh').instance(mode='server').get_plot(violin).state
示例#7
0
def violin_areas(df):
    violin = hv.Violin(df, ('nombre_area', 'Area'), ('edad', 'Edad'))
    violin.options(height=500, width=500)
    return hv.renderer('bokeh').instance(mode='server').get_plot(violin).state