def custom_color(sample_to_label, samples_dendro_leaves, color_scale='Spectral'):
    # Sample label fragmentation
    sample_to_label = sample_to_label.astype(str).fillna('unkown')
    label_leaves = [str(sample_to_label[x]) for x in samples_dendro_leaves]
    uni_labels = list(np.unique(sample_to_label))
    uni_len = len(uni_labels)
    uni_range = range(uni_len)
    uni_normal = [x/uni_range[-1] for x in uni_range]
    val_label = pd.Series(uni_range, index=uni_labels)
    val_set = [val_label[x] for x in label_leaves]

    
    colors = cl.scales[str(min(max(uni_len, 3), 11))]['div']['Spectral']
    if uni_len > len(colors):
        if uni_len > 20:
            colors = cl.to_rgb(cl.interp(colors, 20))
            for i in range(uni_len - 20):
                i = i % 20
                colors.append(colors[i])
        else:
            colors = cl.to_rgb(cl.interp(colors, uni_len))
    colors_legend = [tuple(map(lambda x:x/255, x)) for x in cl.to_numeric(colors)]
    c_map_legend = list(zip(uni_range, colors_legend))
    c_map = list(zip(uni_normal, colors))
    return c_map, c_map_legend, val_set, val_label
Esempio n. 2
0
def pie_chart_product(data):
    '''
    pie chart for products
    '''
    pie_chart = result_df.groupby(['Product_name',
                                   'Brand_name']).agg({'fileIndex': 'count'})
    pie_chart.reset_index(inplace=True)
    pie_chart.sort_values(by='fileIndex', inplace=True, ascending=False)
    pie_chart = pie_chart.iloc[:20]

    bupu = cl.scales['9']['seq']['BuPu']

    data_g = []
    tr_p = go.Pie(labels=pie_chart['Product_name'],
                  values=pie_chart['fileIndex'],
                  text=pie_chart['Brand_name'],
                  hoverinfo='text+label+value+percent',
                  textinfo='label+percent',
                  textfont=dict(size=13),
                  marker=dict(colors=cl.interp(bupu, 20),
                              line=dict(color='#000000', width=1)))
    data_g.append(tr_p)
    layout = go.Layout(title="Top20 most popular products",
                       titlefont=dict(size=35))
    fig = go.Figure(data=data_g, layout=layout)
    plotly.offline.plot(fig, filename='products.html')
Esempio n. 3
0
def generate_colors_palette(data, isDict=True, forceString=False):
    '''
    This function builds a dict containing color for each element in data.

    Parameters
        - data: Container of objects containing name of objects which need specific color
        - isDict: Boolean which indicates if data is a Dict (if True, keys will be used / by default, True)
        - forceString: Boolean which indicates if key of colors dictionary must be converted to string (by default, False)

    Return
        - colors: Dict containing color for each object (key: name of object, value: color (string))
    '''

    palette = None
    if len(data) <=8:
        palette = cl.scales['8']['qual']['Paired']
    else:
        size = len(data)
        # Bug in colorlover (see issues on GitHub page of project)
        # We artificially increase size until no exception is thrown (i.e. mapping has been successfully created)
        while not palette:
            try:
                palette = cl.interp(cl.scales['11']['div']['Spectral'], size)
            except:
                size += 1
    colors = {(name if not forceString else str(name)): palette[index] for index, name in enumerate(data.keys() if isDict else data)}
    return colors
Esempio n. 4
0
    def __init__(self, time_by_forces: ndarray, step_size: float):

        forces_by_time = np.array(time_by_forces).T
        motor_unit_count, steps = forces_by_time.shape
        sim_duration = steps * step_size
        times = np.arange(0.0, sim_duration, step_size)

        # Setting colors for plot.
        potvin_scheme = [
            'rgb(115, 0, 0)', 'rgb(252, 33, 23)', 'rgb(230, 185, 43)',
            'rgb(107, 211, 100)', 'rgb(52, 211, 240)', 'rgb(36, 81, 252)',
            'rgb(0, 6, 130)'
        ]

        # It's hacky but also sorta cool.
        c = cl.to_rgb(cl.interp(potvin_scheme, motor_unit_count))
        c = [val.replace('rgb', 'rgba') for val in c]
        c = [val.replace(')', ',{})') for val in c]

        # Assing non-public attributes
        self._step_size = step_size
        self._forces_by_time = forces_by_time
        self._c = c
        self._times = times

        # Assign public attributes
        self.motor_unit_count = motor_unit_count
Esempio n. 5
0
def get_singlecell_colors(cell_list, palette="paired", return_str=False):
    u_cells = list(set(cell_list))
    color_list = cl.to_rgb(cl.interp(my_palette_dict[palette], len(u_cells)))
    if not return_str:
        color_list = [rgb_to_list(i) for i in color_list]
    group_colors = dict(zip(u_cells, color_list))
    return group_colors
def create_topic_description_table(topic_df):
    """Create the topic descriptions table."""
    bupu = cl.scales['9']['div']['RdYlGn']
    colors = cl.interp(bupu, 16)  # Map color scale to 16 bins
    # cl.to_html(colors) # html for the colorscale

    trace0 = go.Table(
        columnorder=[1, 2],
        columnwidth=[80, 300],
        header=dict(values=["<b>TOPIC NUMBER</b>", "<b>TOPIC DESCRIPTION</b>"],
                    line=dict(color='white'),
                    fill=dict(color='white'),
                    align=['center'],
                    font=dict(color='black', size=14),
                    height=80),
        cells=dict(
            values=[topic_df.dominant_topic_num, topic_df.topic_description],
            line=dict(color=[
                np.array(colors)[topic_df.topic_size],
                np.array(colors)[topic_df.topic_size]
            ]),
            fill=dict(color=[
                np.array(colors)[topic_df.topic_size],
                np.array(colors)[topic_df.topic_size]
            ]),
            align=['center', 'left'],
            font=dict(color='black', size=12)))

    data = [trace0]
    plotly.offline.plot(data,
                        filename='templates/topic_descriptions.html',
                        auto_open=False)
Esempio n. 7
0
def generate_cluster_colors(num):
    """Generate a list of colors given number needed.

    Arguments:
        num (int): Number of colors needed. n <= 35.

    Returns:
        list: strings containing RGB-style strings e.g. rgb(255,255,255).
    """

    # Selects a random colorscale (RGB) depending on number of colors needed
    if num < 12:
        c = cl.scales[str(num)]['qual']
        c = c[random.choice(list(c))]
    else:
        num_rounded = int(math.ceil(num / 10)) * 10
        c = cl.to_rgb(cl.interp(cl.scales['12']['qual']['Paired'],
                                num_rounded))
    c = cl.to_numeric(sample(c, int(num)))

    # Converts selected colorscale to HSL, darkens the color if it is too light,
    # convert it to rgb string and return
    c_rgb = []
    for color in c:
        hls = colorsys.rgb_to_hls(color[0] / 255, color[1] / 255,
                                  color[2] / 255)
        if hls[1] < 0.6:  # Darkens the color if it is too light (HLS = [0]Hue [1]Lightness [2]Saturation)
            rgb = colorsys.hls_to_rgb(hls[0], 0.6, hls[2])
        else:
            rgb = colorsys.hls_to_rgb(hls[0], hls[1], hls[2])
        rgb_str = "rgb(" + str(rgb[0] * 255) + "," + str(
            rgb[1] * 255) + "," + str(rgb[2] * 255) + ")"
        c_rgb.append(rgb_str)

    return c_rgb
Esempio n. 8
0
def get_palette(aeb_count):
    '''Get the suitable palette to plot for some number of aeb graphs, where each aeb is a color.'''
    if aeb_count <= 8:
        palette = cl.scales[str(max(3, aeb_count))]['qual']['Set2']
    else:
        palette = cl.interp(cl.scales['8']['qual']['Set2'], aeb_count)
    return palette
def create_k_clusters(k, X, text=''):
    """
    Creates a list of scatter objects for clustering visualization
    
    Parameters:
    ----------------
    k: int
        Number of clusters to fit data to
    X: numpy array
        n x 2 array with coordinates of each point   
    text: string or array of strings
        Text which will pop up when hovering over data points
    Returns:    
    ----------------
    data: list of plotly.graph_objs.Scatter objects
         Contains Scatter objects for two dimensional plotting    
    """
    data = []
    colors_k_bins = cl.to_rgb(cl.interp(cl.scales['11']['qual']['Paired'], k))        
    class_labels_k = KMeans(k).fit_predict(X)    
    for i,j in enumerate(colors_k_bins):
        
        data.append(go.Scatter(x = X[class_labels_k==i,0],
                               y = X[class_labels_k==i,1],
                               text = text,
                               mode = 'markers',
                               marker=go.scatter.Marker(color=j)                             
                               )
                   )        
    return data
Esempio n. 10
0
def get_palette(size):
    '''Get the suitable palette of a certain size'''
    if size <= 8:
        palette = cl.scales[str(max(3, size))]['qual']['Set2']
    else:
        palette = cl.interp(cl.scales['8']['qual']['Set2'], size)
    return palette
Esempio n. 11
0
def get_plot_colors(max_colors, color_format="pyplot"):
    """Generate colors for plotting."""
    colors = cl.scales["11"]["qual"]["Paired"]
    if max_colors > len(colors):
        colors = cl.to_rgb(cl.interp(colors, max_colors))
    if color_format == "pyplot":
        return [[j / 255.0 for j in c] for c in cl.to_numeric(colors)]
    return colors
Esempio n. 12
0
def get_plot_colors(max_colors, color_format='pyplot'):
    """Generate colors for plotting."""
    colors = cl.scales['11']['qual']['Paired']
    if max_colors > len(colors):
        colors = cl.to_rgb(cl.interp(colors, max_colors))
    if color_format == 'pyplot':
        return [[j / 255.0 for j in c] for c in cl.to_numeric(colors)]
    return colors
Esempio n. 13
0
    def make_color_list(self, position_data):

        ### make color list for each clade
        clade_list = position_data["clade"].unique()
        color_list = cl.scales['11']['div']['Spectral']
        color_list = cl.interp(color_list, len(clade_list))
        color_list = dict(zip(clade_list, color_list))

        return color_list
Esempio n. 14
0
def init_data_store():
    print("INITIALIZING GRAPHS...")
    store = {'graphData': {}, 'colorMaps': {}}
    store['graphData']['activeRanges'] = {}
    store['graphData']['pseudoMsgCount'] = {}
    store['graphData']['actualMsgCount'] = {}
    store['colorMaps']['colorGrad'] = cl.interp(COLOR_RANGE, COLOR_SCALE)
    store['colorMaps']['consumer2color'] = {}

    return store
def colorscale(colorPalette, color_step):
    color_scale = cl.scales['3']['div'][colorPalette]
    color_scale = cl.interp(color_scale, color_step)

    # create a list of pairs of (value, color) to map to a colorbar -- value in [0,0.2,0.4,0.6,0.8,1]
    colorbar_scale = [[i / 100, color] for i, color in zip(
        range(0, 101, 20), color_scale[0::int(len(color_scale) / 5)] +
        [color_scale[-1]])]

    return color_scale, colorbar_scale
Esempio n. 16
0
def get_colors(number_of_colors, colors=None, cl_scales=['9', 'qual', 'Set1']):
    if colors is None:
        color_scale = cl.scales[cl_scales[0]][cl_scales[1]][cl_scales[2]]
        if number_of_colors > int(cl_scales[0]):
            print('interpolated')
            colors = cl.interp(color_scale, 500)
            colors = [colors[int(x)] for x in np.arange(0, 500,
                                                        int(np.floor(500 / number_of_colors)))]
        else:
            colors = color_scale
    return colors
Esempio n. 17
0
    def __init__(self):
        self._min = 0
        vals = list(self.all_values())
        if len(vals) > 0:
            self._max = max(vals) * 2
        else:
            self._max = 0

        self._n = 500
        sch = colorlover.scales['9']['seq']['BuPu']
        self._scheme = colorlover.interp(sch, 500)
Esempio n. 18
0
def color_palette(elements, ptype='qual', palette='Paired'):
    n_element = len(elements)
    if n_element < 3:
        colors = cl.scales['3'][ptype][palette][:n_element]
    elif n_element <= 11:
        cnt = str(n_element)
        colors = cl.scales[cnt][ptype][palette]
    else:
        cnt = '11'
        palettes = cl.scales[cnt][ptype][palette]
        colors = cl.interp(palettes, n_element)
    colors = cl.to_rgb(colors)
    return dict(zip(elements, colors))
Esempio n. 19
0
    def drawActionSeqGantt(self):
        import plotly.figure_factory as ff
        import colorlover as cl
        import plotly.graph_objects as go
        from plotly.subplots import make_subplots
        '''
        '''
        self.checkActionSeq()
        multiPerm = self._seq.convert2MultiPerm(self._robNum)
        print(multiPerm)
        actionRobLst = [[] for x in range(self._robNum)]
        for act in self._seq:
            actionRobLst[act.robID].append(act)
        df = []
        for robID in range(self._robNum):
            for ind in range(0, len(actionRobLst[robID]), 2):
                dic = dict(Task='rob' + str(robID),
                           Start=actionRobLst[robID][ind].eventTime,
                           Finish=actionRobLst[robID][ind + 1].eventTime,
                           Resource='Task' +
                           str(actionRobLst[robID][ind].taskID))
                df.append(dic)
            # if robID > 1:
            #     break
        if self._taskNum <= 10:
            colorLst = cl.scales[str(self._taskNum)]['qual']['Paired']
        else:
            colorLst = cl.scales['10']['qual']['Paired']
            colorLst = cl.interp(colorLst, 500)
        colorDic = dict()
        for taskID in range(self._taskNum):
            colorDic['Task' + str(taskID)] = colorLst[taskID]

        print(colorDic)
        print(df)
        # print(actionRobLst)
        # exit()
        # for act in self._seq:
        #     pass
        #     # df.append(dict(Task = ''))
        # for robID in range(self._robNum):
        #     df.append(dict(Task = 'rob'+ str(robID), Start = 1, Finish = 5))
        # fig = ff.create_gantt(df, colors=colorDic, index_col= 'Resource', show_colorbar=True, group_tasks=True)
        fig = ff.create_gantt(df,
                              colors=colorLst,
                              index_col='Resource',
                              show_colorbar=True,
                              group_tasks=True)
        fig['layout']['xaxis']['type'] = 'linear'
        fig['layout']['xaxis']['zeroline'] = True
        fig.show()
Esempio n. 20
0
def id_survey(frequency, intensity, catdict):
    """
        Function for plotting predicted lines as stick spectra
        on top of a broadband survey spectrum.
        
        Frequency and intensity are 1D arrays of the spectrum
        frequency and intensity.
        
        catdict is a dictionary with keys corresponding to
        the name of the molecule, and values corresponding
        to dataframes of the parsed .cat file.
    """
    plots = list()

    # Plot out the experiment first

    plots.append(
        go.Scatter(x=frequency, y=intensity, marker={"color": (0., 0., 0.)}))

    # Set the colour palette, and interpolate colours to
    # accommodate for the number of cat files
    spectral_palette = cl.scales["8"]["div"]["Spectral"]
    colors = cl.interp(spectral_palette, len(catdict))

    for name, color in zip(catdict, colors):
        plots.append(
            go.Bar(x=catdict[name]["Frequency"],
                   y=np.abs(catdict[name]["Intensity"]),
                   name=name,
                   width=2.,
                   marker={"color": color}))

    layout = go.Layout(
        xaxis={
            "title": "Frequency (MHz)",
            "range": [np.min(frequency), np.max(frequency)],
            "tickformat": "0.2f"
        },
        yaxis={"title": ""},
        autosize=False,
        height=800,
        width=1000,
        paper_bgcolor="#f0f0f0",
        plot_bgcolor="#f0f0f0",
    )

    fig = go.Figure(data=plots, layout=layout)

    iplot(fig)
    return fig
Esempio n. 21
0
def color_scale_interp(
    input_num,
    max_num,
    min_num,
    color_mesh_size=80,
    hex_mode=True,
):
    """
    """
    # | - color_scale_interp
    #     cl.scales["8"]["seq"]["Purples"]

    black_white_cs = [
        'rgb(0,0,0)',
        'rgb(255,255,255)',
    ]

    black_red_cs = [
        'rgb(0,0,0)',
        'rgb(255,0,0)',
    ]

    color_scale_i = black_red_cs

    color_scale_i = cl.scales["8"]["seq"]["Greys"][::-1]
    #     color_scale_i = cl.scales["8"]["seq"]["Purples"]
    #     color_scale_i = cl.scales['3']['div']['RdYlBu']

    color_scale = cl.interp(
        color_scale_i,
        color_mesh_size,
    )

    color_scale = cl.to_rgb(color_scale)

    # Converting RGB string representatino to tuple
    color_scale = cl.to_numeric(color_scale)

    input_norm = ((input_num - min_num) / (max_num - min_num))

    cs_index = round(input_norm * len(color_scale)) - 1
    if cs_index == -1:
        cs_index = 0

    color_out = color_scale[cs_index]

    if hex_mode:
        color_out = rgb_to_hex(color_out)

    return (color_out)
Esempio n. 22
0
 def setColorSet(self, dimensions='12', type='qual', dataset='Paired'):
     if dimensions in cl.scales:
         if type in cl.scales[dimensions]:
             if dataset in cl.scales[dimensions][type]:
                 color_set = cl.scales[dimensions][type][dataset]
                 self.colorset = (dimensions, type, dataset)
                 if (len(self.data.components) > len(color_set)):
                     color_set = cl.interp(color_set,
                                           len(self.data.components))
                 color_set = cl.to_rgb(color_set)
                 for i, component in enumerate(self.data.components):
                     self.data.get_component(component).color = color_set[i]
                 return True
     return False
Esempio n. 23
0
def cache_raw_data(net_type, N=25, p=0.5, m=3, k=3):
    global model, data2, end, colors_c, stocks, initiated, agents
    if m >= N:
        N = m + 1
    agents = fresh_agents if N >= len(fresh_agents) else fresh_agents[0:N]
    agents = [deepcopy(x) for x in agents]
    model = FinNetwork("Net 1", agents, net_type=net_type, p=p, m=m, k=k)
    stocks = [x.name for x in agents]
    colors_ = (cl.to_rgb(
        cl.interp(cl.scales['6']['qual']['Set1'],
                  len(stocks) * 20)))
    colors_c = np.asarray(colors_)[np.arange(0, len(stocks) * 20, 20)]
    end = datetime.date.today()
    print('Loaded raw data')
    return 'loaded'
Esempio n. 24
0
def palette_de_couleurs(nb_of_colors):
    """ Input: the length of the list with different colors
        Output: a list with rgb colors in an ascending order
        """
    
    bupu = cl.scales['9']['seq']['Reds']
    bupu500 = cl.interp( bupu, nb_of_colors ) # Map color scale to 500 bins
    colors=cl.to_rgb(bupu500)
    for i in range(nb_of_colors):
        color= colors[i][3:]
        c=array((0,0,0))
        for j in range(3):
            c[j]=color.strip("()").split(",")[j]
        colors[i]=c
    return colors
Esempio n. 25
0
def preload_data_store():
    store = {'graphData': {}, 'colorMaps': {}}
    store['graphData']['activeRanges'] = {'t1': 50, 't2': 25, 't3': 25}
    store['graphData']['pseudoMsgCount'] = {'t1': 50, 't2': 20, 't3': 100}
    store['graphData']['actualMsgCount'] = {'t1': 50, 't2': 30, 't3': 100}
    store['colorMaps']['colorGrad'] = cl.interp(COLOR_RANGE, COLOR_SCALE)
    store['colorMaps']['consumer2color'] = {}

    # Assign colors
    for c in store['graphData']['activeRanges'].keys():
        assign_color(consumer=c,
                     consumer2color=store['colorMaps']['consumer2color'],
                     color_grad=store['colorMaps']['colorGrad'])

    return store
Esempio n. 26
0
    def draw_stack_bar(self, key):
        count_matrix = []
        data_of_key, labels = self.get_value_by_key(key)
        all_uniques_cells = sorted(list(BACKGROUND_COLOR_DICT.keys()))
        for i in range(len(data_of_key)):
            uniques, counts = np.unique(data_of_key[i], return_counts= True)
            temp = []

            # sum_counts = np.sum(counts)
            # counts = counts/sum_counts
            i = 0
            print(uniques, all_uniques_cells)
            for j in all_uniques_cells:
                if i >= len(uniques):
                    temp.append(0)
                elif j == uniques[i]:
                    temp.append(counts[i])
                    i += 1
                else:
                    temp.append(0)

            count_matrix.append(temp)
        np_matrix = np.array(count_matrix)
        np_matrix = np_matrix.T
        bupu = cl.scales['9']['seq']['YlOrBr']
        bupux = cl.interp(bupu, 100)
        gap = math.floor(100/len(np_matrix))
        stacked_data = []
        for i in range(len(np_matrix)):
            trace0 = go.Bar(
                x = labels,
                y = np_matrix[i],
                name = all_uniques_cells[i],
                marker = dict(
                    # cmax=len(np_matrix),
                    # cmin=0,
                    # colorscale='Viridis',
                    color = bupux[gap * i]
                )
            )
            stacked_data.append(trace0)

        layout = go.Layout(
            barmode = 'stack'
        )
        fig = go.Figure(data=stacked_data, layout=layout)
        return py.iplot(fig, filename='stacked-bar')
Esempio n. 27
0
def make_table_plot(name,set,site_list,loci_dict,filename):
    ryg = cl.scales['11']['div']['RdYlGn']
    ryg100 = cl.interp(ryg, 100)
    table_values = [set]
    colors = [['grey' for i in set]]
    for sample1 in set:
        table_line = []
        table_color = []
        for sample2 in set:
            correct_calls = []
            if sample1 == sample2:
                cell_percent = 'X'
                table_line.append(cell_percent)
                cell_color = 'grey'
            else:
                for locus in site_list:
                    if loci_dict[sample1][locus]['genotype'] == loci_dict[sample2][locus]['genotype']:
                        correct_calls.append(1)
                    else:
                        correct_calls.append(0)
                cell_percent = int((sum(correct_calls)/len(correct_calls))*100)
                cell_color = ryg100[cell_percent-1]
                table_line.append(str(cell_percent)+'%')
            table_color.append(cell_color)
        table_values.append(table_line)
        colors.append(table_color)
    trace = go.Table(
        header = dict(
            values=['']+set,
            line = dict(color = '#506784'),
            fill=dict(color='grey'),
            font = dict(color = 'white', size = 12)
        ),
        cells = dict(
            values=table_values,
            line = dict(color = '#506784'),
            fill = dict(color = colors),
            font=dict(color=['white','lightgrey'], size=12)
        )
    )
    layout = go.Layout(
        title='percentage of same calls {}'.format(name),
        width=1500,
        height=640
    )
    fig = dict(data=[trace], layout=layout)
    py.image.save_as(fig, filename=filename)
Esempio n. 28
0
File: Mint.py Progetto: LSARP/mint
def plot_1(n_clicks, n_cols, options):
    if (n_clicks is None) or (mint.rt_projections is None):
        raise PreventUpdate
    files = mint.crosstab.columns
    labels = mint.crosstab.index
    fig = make_subplots(rows=len(labels) // n_cols + 1,
                        cols=n_cols,
                        subplot_titles=labels)

    if len(files) < 13:
        # largest color set in colorlover is 12
        colors = cl.scales['12']['qual']['Paired']
    else:
        colors = cl.interp(cl.scales['12']['qual']['Paired'], len(files))

    for label_i, label in enumerate(labels):
        for file_i, file in enumerate(files):

            data = mint.rt_projections[label][file]
            ndx_r = (label_i // n_cols) + 1
            ndx_c = label_i % n_cols + 1

            fig.add_trace(
                go.Scatter(x=data.index,
                           y=data.values,
                           name=basename(file),
                           mode='lines',
                           legendgroup=file_i,
                           showlegend=(label_i == 0),
                           marker_color=colors[file_i],
                           text=file),
                row=ndx_r,
                col=ndx_c,
            )

            fig.update_xaxes(title_text="Retention Time", row=ndx_r, col=ndx_c)
            fig.update_yaxes(title_text="Intensity", row=ndx_r, col=ndx_c)

    fig.update_layout(height=200 * len(labels), title_text="Peak Shapes")
    fig.update_layout(xaxis={'title': 'test'})

    if 'legend_horizontal' in options:
        fig.update_layout(legend_orientation="h")

    if 'legend' in options:
        fig.update_layout(showlegend=True)
    return fig
Esempio n. 29
0
def plot_gaussian():
    x = arange(0, 30, .05)

    colorscale = cl.scales['9']['seq']['PuBuGn']
    scales = cl.interp(colorscale, 30)

    traces = []
    for i, K in enumerate(arange(1, 11)):

        y = norm.pdf(x, scale=K) / norm.pdf(0, scale=K)
        traces.append(
            dict(
                x=x,
                y=y,
                name=f'{K:d}mm',
                marker=dict(color=scales[i * 2 + 5], ),
            ))

    fig = go.Figure(data=traces,
                    layout=go.Layout(
                        xaxis=dict(
                            linecolor='black',
                            gridcolor='black',
                            dtick=4,
                            tickfont=dict(size=8, ),
                        ),
                        yaxis=dict(
                            linecolor='black',
                            gridcolor='black',
                            tickmode='array',
                            tickvals=[0, 1],
                            ticktext=[0, 'MAX'],
                            tickfont=dict(size=8, ),
                        ),
                        legend=dict(
                            title=dict(
                                text='kernel σ',
                                font=dict(size=10, ),
                            ),
                            itemwidth=30,
                            font=dict(size=8, ),
                        ),
                    ))

    return fig
Esempio n. 30
0
def get_colours(n_classes, rettype='numeric255'):
    n_categorical_colours = 11

    if n_classes <= n_categorical_colours:
        #     colours = cl.to_numeric(cl.scales[str(nClasses)]['div']['Spectral'])
        colours = to_numeric(cl.scales[str(n_classes)]['div']['Spectral'])
    else:
        colours = to_numeric(
            cl.interp(cl.scales[str(n_categorical_colours)]['div']['Spectral'],
                      n_classes))

    if rettype == 'numeric255':
        return colours
    if rettype == 'numeric1':
        return (np.array(colours) / 255.).tolist()
    if rettype == 'hex':
        return to_hex(colours)

    raise Exception('Unknown type {}'.format(rettype))
Esempio n. 31
0
def plotPrettyColours(data, grouping):
    
    #make directories for saving plot htmls
    os.makedirs(clustering_evaluation_dir, exist_ok=True)
    os.makedirs(cluster_analysis_dir, exist_ok=True)
   
    if grouping == 'experiments':
        colour_seq = ['Reds','Oranges','YlOrBr','YlGn','Greens','BuGn','Blues','RdPu',
                      'PuBu','Purples','PuRd','YlGnBu','YlOrRd']
        df = pd.DataFrame(data.experiment_name.unique(), columns=['name'])
        df['root'] = df.applymap(lambda x: '_'.join(x.split('_',2)[0:2]))
        
    elif grouping == 'elec_bin':
        colour_seq = ['YlGn','PuRd','Blues','YlOrBr','Greens','RdPu','Oranges',
                      'Purples','PuBu','BuGn','Reds']
        df = data['elec_bin'].reset_index().rename({'elec_bin':'root', 'k':'name'}, axis=1)

    df['root'] = df.root.astype('category')                
    df.root.cat.rename_categories(colour_seq[:len(df.root.cat.categories)], inplace=True)
    col_temp = df.groupby('root').apply(lambda x: len(x))
    
    my_cols = list()
    for c, v in col_temp.items():
        try:
            i = 0
            gcol=list()
            while i < v:
                gcol.append(cl.scales['9']['seq'][c][2+i])
                i+=1
        except:
            i = 0
            gcol=list()
            jump = int(80/v)
            while i < v:
                gcol.append(cl.to_rgb(cl.interp(cl.scales['9']['seq'][c], 100))[-1-jump*i])
                i+=1
        my_cols+=gcol
    
    colours = dict(zip(df.name, my_cols))
    
    return colours
def viewSections(width = 800, height = 400, cs = None, layNb = 2,
                    linesize = 3, title = 'Cross section'):
    """
    Plot multiple cross-sections data on a graph.
    Parameters
    ----------
    variable: width
        Figure width.
    variable: height
        Figure height.
    variable: cs
        Cross-sections dataset.
    variable: layNb
        Number of layer to plot.
    variable: linesize
        Requested size for the line.
    variable: title
        Title of the graph.
    """

    colors = cl.scales['9']['div']['RdYlBu']
    hist = cl.interp( colors, layNb )
    colorrgb = cl.to_rgb( hist )

    nlay = layNb - 1

    lay = {}
    toplay = cs[nlay].top
    cs[nlay].ndepo = cs[nlay].depo
    cs[nlay].ntop = toplay

    botlay = cs[nlay].top - cs[nlay].depo

    for i in range(nlay-1,-1,-1):
        tmp1 = cs[i+1].ndepo - cs[i].depo
        tmp2 = cs[i+1].ndepo - tmp1.clip(min=0)
        cs[i].ndepo = tmp2
        cs[i].ntop = botlay + tmp2

    trace = {}
    data = []

    for i in range(1,nlay):
        trace[i-1] = Scatter(
            x=cs[i].dist,
            y=cs[i].ntop,
            mode='lines',
            name="layer "+str(i),
            line=dict(
                shape='line',
                width = linesize-1,
                color = colorrgb[i-1] #,
                #dash = 'dash'
            )
        )
        data.append(trace[i-1])

    # Top line
    trace[nlay] = Scatter(
        x=cs[nlay].dist,
        y=cs[nlay].top,
        mode='lines',
        name="top",
        line=dict(
            shape='line',
            width = linesize,
            color = 'rgb(102, 102, 102)'
        )
    )
    data.append(trace[nlay])

    # Bottom line
    trace[nlay+1] = Scatter(
        x=cs[nlay].dist,
        y=cs[nlay].top - cs[nlay].depo,
        mode='lines',
        name="base",
        line=dict(
            shape='line',
            width = linesize,
            color = 'rgb(102, 102, 102)'
        )
    )
    data.append(trace[nlay+1])

    layout = dict(
            title=title,
            width=width,
            height=height
    )

    fig = Figure(data=data, layout=layout)
    plotly.offline.iplot(fig)

    return
def plot_scatter_comparison(title, x_axis_title, y_axis_title, mat_1, mat_2, plot_out, color_vector=None, qqplot=False):

    L = mat_1.shape[0]
    upper_triangular_indices = np.triu_indices(L, k=1)

    score_1 = mat_1[upper_triangular_indices]
    score_2 = mat_2[upper_triangular_indices]

    lin_reg_x = list(np.arange(
        np.min([np.min(score_1),np.min(score_2)]),
        np.max([np.max(score_1),np.max(score_2)]),
        0.05))
    slope, intercept, rvalue, pvalue, stderr = linregress(score_1, score_2)
    lin_reg_y = [intercept + slope * x for x in lin_reg_x]


    text = ["i: " + str(i+1) + ", j: " + str(j+1) for i,j in zip(upper_triangular_indices[0], upper_triangular_indices[1])]

    if color_vector is not None:
        text = [text[ij] + ", sum_nia * sum_njb: " + str(color_vector[ij]) for ij in range(len(text))]
        color_scale = cl.interp(cl.scales['3']['seq']['Reds'], 400)
        color_vector = [color_scale[i - 1] for i in color_vector]
        opacity = 1
    else:
        color_vector = 'rgb(31,120,180)'
        opacity = 1

    data=[]


    data.append(
        go.Scattergl(
            x=[np.min([np.min(score_1), np.min(score_2)]), np.min([np.max(score_1), np.max(score_2)])],
            y=[np.min([np.min(score_1), np.min(score_2)]), np.min([np.max(score_1), np.max(score_2)])],
            mode='lines',
            line=dict(color='lightgrey',
                      width=3,
                      dash='dash'
                      ),
            showlegend=False
        )
    )

    data.append(
        go.Scattergl(
            x= score_1,
            y= score_2,
            text = text,
            mode = 'markers',
            marker=dict(
                opacity=opacity,
                color=color_vector),
            hoverinfo="x+y+text",
            showlegend=False
        )
    )

    if qqplot:

        index_sorted_i = np.argsort(score_1)
        index_sorted_j = np.argsort(score_2)

        text_sorted = ["i: " + str(i+1) + ", j: " + str(j+1) for i,j in zip(
            upper_triangular_indices[0][index_sorted_i],
            upper_triangular_indices[1][index_sorted_j]
        )]


        data.append(
            go.Scattergl(
                x=sorted(score_1),
                y=sorted(score_2),
                text=text_sorted,
                mode='markers',
                marker=dict(
                    color="rgb(255,127,0)"),
                hoverinfo="x+y+text",
                showlegend=False
            )
        )


    data.append(
        go.Scattergl(
            x=lin_reg_x,
            y=lin_reg_y,
            mode='lines',
            line=dict(color="black",
                      width=4),#"rgb(166,206,227)"),#"rgb(51,160,44)"),
            showlegend=False
        )
    )




    plot = {
        "data": data,
        "layout" : go.Layout(
            annotations=go.Annotations([
                go.Annotation(
                    x=np.percentile(lin_reg_x, 95),
                    y=np.percentile(lin_reg_y, 95),
                    showarrow=True,
                    ax=30,
                    ay=50,
                    arrowcolor='black',
                    arrowside="start",
                    text='y = {0} + {1}x'.format(np.round(intercept, decimals=3),np.round(slope, decimals=3)),
                    font=dict(color="black", size=18),
                    xref='x1',
                    yref='y1'
                )
            ]),
            title = title,
            font=dict(size=18),
            yaxis1 = dict(
                title=y_axis_title,
                exponentformat="e",
                showexponent='All',
                scaleratio=1.0,
                scaleanchor='x',
            ),
            xaxis1 = dict(
                title=x_axis_title,
                exponentformat="e",
                showexponent='All',
                scaleratio=1.0,
                scaleanchor='y'
            )
        )
    }


    plotly_plot(plot, filename=plot_out, auto_open=False)
Esempio n. 34
0
	def _interp(colors,N):
		try:
			return cl.interp(colors,N)
		except:
			return _interp(colors,N+1)
def viewSection(width = 800, height = 400, cs = None, dnlay = None,
                rangeX = None, rangeY = None, linesize = 3, title = 'Cross section'):
    """
    Plot multiple cross-sections data on a graph.
    Parameters
    ----------
    variable: width
        Figure width.
    variable: height
        Figure height.
    variable: cs
        Cross-sections dataset.
    variable: dnlay
        Layer step to plot the cross-section.
    variable: rangeX, rangeY
        Extent of the cross section plot.
    variable: linesize
        Requested size for the line.
    variable: title
        Title of the graph.
    """
    nlay = len(cs.secDep)
    colors = cl.scales['9']['div']['BrBG']
    hist = cl.interp( colors, nlay )
    colorrgb = cl.to_rgb( hist )

    trace = {}
    data = []

    trace[0] = Scatter(
        x=cs.dist,
        y=cs.secDep[0],
        mode='lines',
        line=dict(
            shape='line',
            width = linesize+2,
            color = 'rgb(0, 0, 0)'
        )
    )
    data.append(trace[0])

    for i in range(1,nlay-1,dnlay):
        trace[i] = Scatter(
            x=cs.dist,
            y=cs.secDep[i],
            mode='lines',
            line=dict(
                shape='line',
                width = linesize,
                color = 'rgb(0,0,0)'
            ),
            opacity=0.5,
            fill='tonexty',
            fillcolor=colorrgb[i]
        )
        data.append(trace[i])

    trace[nlay-1] = Scatter(
        x=cs.dist,
        y=cs.secDep[nlay-1],
        mode='lines',
        line=dict(
            shape='line',
            width = linesize+2,
            color = 'rgb(0, 0, 0)'
        ),
        fill='tonexty',
        fillcolor=colorrgb[nlay-1]
    )
    data.append(trace[nlay-1])

    trace[nlay] = Scatter(
        x=cs.dist,
        y=cs.secDep[0],
        mode='lines',
        line=dict(
            shape='line',
            width = linesize+2,
            color = 'rgb(0, 0, 0)'
        )
    )
    data.append(trace[nlay])

    if rangeX is not None and rangeY is not None:
        layout = dict(
                title=title,
                font=dict(size=10),
                width=width,
                height=height,
                showlegend = False,
                xaxis=dict(title='distance [m]',
                            range=rangeX,
                            ticks='outside',
                            zeroline=False,
                            showline=True,
                            mirror='ticks'),
                yaxis=dict(title='elevation [m]',
                            range=rangeY,
                            ticks='outside',
                            zeroline=False,
                            showline=True,
                            mirror='ticks')
        )
    else:
        layout = dict(
                title=title,
                font=dict(size=10),
                width=width,
                height=height
        )
    fig = Figure(data=data, layout=layout)
    plotly.offline.iplot(fig)

    return