def plot_the_table(self, df1, colorscale=None): dimension_list = list() trace = None # print(colorscale) colorscale = [ # Let first 10% (0.1) of the values have color rgb(0, 0, 0) [0, "rgb(223, 169, 102)"], [0.1, "rgb(223, 169, 102)"], # Let values between 10-20% of the min and max of z # have color rgb(20, 20, 20) [0.1, "rgb(147, 133, 64)"], [0.2, "rgb(147, 133, 64)"], # Values between 20-30% of the min and max of z # have color rgb(40, 40, 40) [0.2, "rgb(20, 17, 177)"], [0.3, "rgb(20, 17, 177)"], [0.3, "rgb(160, 17, 2)"], [0.4, "rgb(160, 17, 2)"], [0.4, "rgb(80, 80, 80)"], [0.5, "rgb(80, 80, 80)"], [0.5, "rgb(100, 100, 100)"], [0.6, "rgb(100, 100, 100)"], [0.6, "rgb(120, 120, 120)"], [0.7, "rgb(120, 120, 120)"], [0.7, "rgb(140, 140, 140)"], [0.8, "rgb(140, 140, 140)"], [0.8, "rgb(160, 160, 160)"], [0.9, "rgb(160, 160, 160)"], [0.9, "rgb(180, 180, 180)"], [1.0, "rgb(180, 180, 180)"] ] for value in df1.columns: dimension_list.append(dict(label=value, values=df1[value])) if colorscale == None: trace = go.Parcoords(line=dict(color=df1[df1.columns[-1]]), dimensions=dimension_list) else: trace = go.Parcoords(line=dict(color=df1[df1.columns[-1]], colorscale=colorscale), dimensions=dimension_list) data = [trace] layout = None if len(df1.columns) > 35: layout = go.Layout(plot_bgcolor='#E5E5E5', paper_bgcolor='#E5E5E5', dragmode='zoom', width=8000, height=1000) else: layout = go.Layout(plot_bgcolor='#E5E5E5', paper_bgcolor='#E5E5E5', dragmode='zoom', height=1000) return go.Figure(data=data, layout=layout)
def create_parallel_2(by_week_df_2): session_id = str(uuid.uuid4()) activities_df, by_week_df = get_dataframe(session_id) dimensions = [] for i in range(7): dimensions.append( dict(range=[0, 20], label='{}'.format(days_dict[i]), values=by_week_df_2['miles_{}'.format(i)])) data = [ go.Parcoords(line=dict(color=by_week_df['miles'], colorscale='Hot', showscale=True, reversescale=True), opacity=0.5, dimensions=dimensions, hoverinfo='text') ] layout = go.Layout(plot_bgcolor='#E5E5E5', paper_bgcolor='#E5E5E5', title='Miles per week broken down by day') return go.Figure(data=data, layout=layout)
def update_parcoords(loa_range, boa_range, draft_range, velocity_range, disp_range): dff = df[(df['loa'] > loa_range[0]) & (df['loa'] < loa_range[1]) & # (df['lwl'] > lwl_range[0]) & (df['lwl'] < lwl_range[1]) & (df['boa'] > boa_range[0]) & (df['boa'] < boa_range[1]) & # (df['bwl'] > bwl_range[0]) & (df['bwl'] < bwl_range[1]) & (df['draft'] > draft_range[0]) & (df['draft'] < draft_range[1]) & (df['velocity'] > velocity_range[0]) & (df['velocity'] < velocity_range[1]) & (df['vol_disp'] > disp_range[0]) & (df['vol_disp'] < disp_range[1])] return { 'data': [ go.Parcoords(dimensions=[ # dict(label='LWL', values=dff['lwl']), dict(label='LOA', values=dff['loa']), # dict(label='BWL', values=dff['bwl']), dict(label='BOA', values=dff['boa']), dict(label='Draft', values=dff['draft']), dict(label='Vol. displacement', values=dff['vol_disp']), dict(label='Resistance', values=dff['total_resistance']) ]) ] }
def chart_plot(by_week_df): dimensions = [] for i in range(7): dimensions.append( dict(range=[0, 20], constraintrange=[0, 20], label='{}'.format(days_dict[i]), values=by_week_df['miles_{}'.format(i)])) data = [ go.Parcoords(line=dict(color=by_week_df['miles'], colorscale='Hot', showscale=True, reversescale=True), opacity=0.5, dimensions=dimensions, hoverinfo='text') ] layout = go.Layout(plot_bgcolor='#E5E5E5', paper_bgcolor='#E5E5E5', title='Miles per week broken down by day') fig = go.Figure(data=data, layout=layout) return plotly.offline.plot(fig, include_plotlyjs=False, output_type='div')
def parallel_coordinates_window(vis, dimensions, title, line_color='blue', win=None): data = go.Parcoords(line=dict(color=line_color), dimensions=dimensions) return vis._send({'data': [data], 'layout': dict(title=title), 'win': win})
def setUp(self): # Construct initial scatter object self.parcoords = go.Parcoords(name='parcoords A') # Assert initial state d1, d2 = strip_dict_params( self.parcoords, {'type': 'parcoords', 'name': 'parcoords A'} ) assert d1 == d2 # Construct expected results self.expected_toplevel = { 'type': 'parcoords', 'name': 'parcoords A', 'dimensions': [ {'values': [2, 3, 1], 'visible': True}, {'values': [1, 2, 3], 'label': 'dim1'}]} self.layout = go.Layout() self.expected_layout1 = { 'updatemenus': [{}, {'font': {'family': 'courier'}}] } self.expected_layout2 = { 'updatemenus': [{}, {'buttons': [ {}, {}, {'method': 'restyle'}]}] }
def calc_graph(self): graph = [] # PUT THE PARETO CURVE INSIDE data = self.process_generation_total_performance_pareto() data = self.normalize_data(data, self.normalization, self.objectives) data = data.sort_values(['GHG_sys_tonCO2']) dimensions = list([ dict(label=label, values=data[field]) if field != 'individual_name' else dict(ticktext=data[field], label=label, tickvals=list(range(data.shape[0])), values=list(range(data.shape[0]))) for field, label in zip(self.analysis_fields, self.titles) ]) line = dict(color=data['Capex_total_sys_USD'], colorscale='Jet', showscale=True) trace = go.Parcoords(line=line, dimensions=dimensions, labelfont=dict(size=10), rangefont=dict(size=8), tickfont=dict(size=10)) graph.append(trace) return graph
def parcoordsPlot(self, simId, scenario, resultName, numVars): if simId is None or not (scenario and resultName): return '' result = self.getOutValues(simId, scenario, resultName) inputsDF = self.getParameterValues(simId) inputsDF = inputsDF.iloc[ result.index] # select only trials for which we have results corrDF = self.getCorrDF(simId, scenario, resultName) varCount = min(numVars, inputsDF.shape[1]) varNames = corrDF.index[:varCount] self.paraCoordsVars = list(varNames) def appendDim(series, name, constraint=None): d = dict(range=[round(min(series), 2), round(max(series), 2)], label=name, values=series) if constraint: # constrain by selection from distribution plot d['constraintrange'] = constraint dimensions.append(d) dimensions = [] for name in varNames: appendDim(inputsDF[name], name) selected = self.selectedResults appendDim(result, resultName, constraint=[min(selected), max(selected)]) plotData = [ go.Parcoords( line=dict(color=result, colorscale='Jet', showscale=True, reversescale=False, cmin=min(result), cmax=max(result)), dimensions=dimensions, rangefont={'color': 'rgba(255,0,0,0)'}, # zero alpha => invisible ) ] layout = dict( autosize=True, height=500, margin=dict(l=75, r=40, b=35, t=35), hovermode="closest", title='', showlegend=False, legend=dict(font=dict(size=10), orientation='h'), ) figure = dict(data=plotData, layout=layout) return figure
def plot_parallel_coordinate(df): sample = df.sample(frac=0.1, replace=True, random_state=1) fig = go.Figure(data=go.Parcoords(line=dict( color=sample['K_Cluster'], colorscale=[[0, 'purple'], [0.5, 'lightseagreen'], [1, 'gold']], showscale=True, cmin=-5.5, cmax=3), dimensions=list([ dict(range=[0, 3], constraintrange=[0, 3], label='Cluster', values=sample['K_Cluster']), dict(range=[-5.5, 1.5], constraintrange=[-5.5, 1.5], label='Recency', values=sample['Recency']), dict(range=[-.5, 2.5], constraintrange=[-.5, 2.5], label='Frequency', values=sample['Frequency']), dict(range=[-3, 3], constraintrange=[-3, 3], label='Monetary', values=sample['Monetary']) ]))) fig.update_layout(plot_bgcolor='white', paper_bgcolor='white') return fig
def parallelPlot(): """Plot parallel graph for selected variants""" data = [ go.Parcoords( line=dict( color=WWR["WWR"], colorscale='RdBu', showscale=False, #True to show colorscale legend reversescale=False, ), dimensions=list([ dict(range=[0, 5], tickvals=[1, 2, 3, 4], label="Orientation", values=plotOri, ticktext=['East', 'North', 'South', 'West']), assignDict(WWR), assignDict(ShadingActive), assignDict(TotalRadWindow), assignDict(TotalRadEnteredWindow), assignDict(TotalIntGain), assignDict(TotalHeating), assignDict(TotalCooling), assignDict(TotalEnergy), assignDict(DF), assignDict(sDA) ])) ] layout = go.Layout( width=1880, height=888) #plot_bgcolor = '#E5E5E5', paper_bgcolor = '#E5E5E5' fig = go.Figure(data=data, layout=layout) py.offline.plot(fig, filename="parallel.html")
def setUp(self): # Construct initial scatter object self.parcoords = go.Parcoords(name="parcoords A") # Assert initial state d1, d2 = strip_dict_params( self.parcoords, {"type": "parcoords", "name": "parcoords A"} ) assert d1 == d2 # Construct expected results self.expected_toplevel = { "type": "parcoords", "name": "parcoords A", "dimensions": [ {"values": [2, 3, 1], "visible": True}, {"values": [1, 2, 3], "label": "dim1"}, ], } self.layout = go.Layout() self.expected_layout1 = {"updatemenus": [{}, {"font": {"family": "courier"}}]} self.expected_layout2 = { "updatemenus": [{}, {"buttons": [{}, {}, {"method": "restyle"}]}] }
def generate_plot(path, auto_open=True): df = pd.read_csv('result/' + path + '.csv') min_max = df['score'].agg(['min', 'max']) dimensions = [] for dimension in df.columns.values: if dimension != 'score': dimensions.append( dict(range=[0, 1], label=dimension, values=df[dimension])) else: dimensions.append( dict(range=[0, min_max.max()], label=dimension, values=df[dimension])) line = dict(color=df['score'], colorscale='Viridis', showscale=True, reversescale=True, cmin=0, cmax=min_max.max()) data = [go.Parcoords(line=line, dimensions=dimensions)] layout = go.Layout(plot_bgcolor='#E5E5E5', paper_bgcolor='#E5E5E5') fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='result/' + path + '.html', auto_open=auto_open)
def parallel_coordinate(dictionary): color_list = [] for i in dictionary: number_of_rows = len(dictionary[i]) for j in range(number_of_rows): color_list.append((-1) * j) break dimensions = list() for key in dictionary: if key != 'commit_id': temp = dict() temp['range'] = [min(dictionary[key]), max(dictionary[key])] temp['label'] = key temp['values'] = dictionary[key] temp['tickformat'] = '0.2f' dimensions.append(temp) data3 = [ go.Parcoords( line=dict( color=color_list, colorscale='Jet', showscale=True, reversescale=True, cmin=-200, # value =200k cmax=0), dimensions=dimensions) ] fig3 = go.Figure(data=data3) return fig3
def drawParallelCoords(data, accuracyName, dimensionNames, lowerisbetter=True): accuracies = [d[accuracyName] for d in data] accuracy_dim = go.parcats.Dimension( values=accuracies, label="mae", ) if lowerisbetter: cmin = np.min(accuracies) cmax = np.mean(accuracies) + np.std(accuracies) else: cmin = np.mean(accuracies) - np.std(accuracies) cmax = np.max(accuracies) cs = [int(acc / np.max(accuracies) * 255.) for acc in accuracies] colors = ['rgb({},0,0)'.format(c) for c in cs] dimensionList = [] for dimensionName in dimensionNames: d = [d[dimensionName] for d in data] dimensionList.append(dict(range=[np.min(d), np.max(d)], label=dimensionName,values=d)) dimensionList.append(dict(range=[np.min(accuracies), np.max(accuracies)],label=accuracyName,values=accuracies)) data = [go.Parcoords( line = dict(color = accuracies, colorscale = 'Bluered', reversescale=lowerisbetter, showscale = True, cmin = cmin, cmax = cmax), dimensions = list(dimensionList))] return data
def createFigureWidget(self): dimensions = self.dimensions data_lines = [] i = 0 if self.only_subsets == False: colors = [i for r in range(self.data.size)] colorscale = [[0, '#EEEEEE']] else: colors = [] colorscale = [] i = -1 for sset in self.data.subsets: i = i + 1 tmplist = [i for r in range(len(sset.to_index_list()))] colors.extend(tmplist) colorscale.append([i, sset.style.color]) t_color = len(colorscale) if (t_color > 1): for c in colorscale: c[0] = c[0] / (t_color - 1) else: colorscale = [[0, '#EEEEEE'], [1, '#EEEEEE']] for dimension in dimensions: line = {} if hasattr(self.data[dimension].flatten(), 'codes'): line['values'] = self.data[dimension].flatten().codes.tolist() tickvals, tickmask = np.unique( self.data[dimension].flatten().codes, return_index=True) ticktext = self.data[dimension][tickmask] line['tickvals'] = tickvals.tolist() line['ticktext'] = ticktext.tolist() else: line['values'] = self.data[dimension].flatten().tolist() line['label'] = dimension for sset in self.data.subsets: if hasattr(sset[dimension].flatten(), 'codes'): tmplist = sset[dimension].codes.tolist() else: tmplist = sset[dimension].tolist() line['values'].extend(tmplist) data_lines.append(line) data = [ go.Parcoords(line=dict(color=colors, colorscale=colorscale), dimensions=data_lines), ] layout = { 'title': self.options['title'].value, 'xaxis': { 'title': self.options['xaxis'].value, }, 'yaxis': { 'title': self.options['yaxis'].value, } } return FigureWidget(data=data, layout=layout)
def add_trace(self, df): self.traces.append(go.Parcoords( line = dict( color=df['target'], colorscale='Jet', ), dimensions = list( [dict(label = col, values = df[col].values) for col in df.columns] )))
def draw_parallel_coordinate(self): """Draw the parallel coordinate graph.""" # Graph the processed data. data = self.all_data # Create the dimensions for parallel coordinates. dimensions = [ dict( label=column, values=data[column], range=[ math.floor(min(data[column]) * 0.95), math.ceil(max(data[column]) * 1.05) ] ) for column in data.columns[:-1] ] # Find the number of toads selected. toad_num = len(self.selected_toad) # Pick proper color. color = colorlover.scales["7"]["qual"]["Dark2"] # Find the color scale list. color_scale = [ [1 * index / (toad_num - 1), color[index]] for index in range(toad_num) ] if toad_num > 1 else [[0, color[0]]] # Create the parallel coordinate. parallel_coordinate = [ go.Parcoords( line=dict( color=data["Numerical ID"], colorscale=color_scale ), dimensions=dimensions ) ] layout = go.Layout(height=750) # Get the color toad matches. color_toad = [ [color[index], toad] for index, toad in enumerate(self.selected_toad) ] # Return the html div to frontend. return jsonify( plot=plot( go.Figure(data=parallel_coordinate, layout=layout), show_link=False, output_type="div", include_plotlyjs=False ), color_toad=color_toad )
def __generate_trace(self, points: pd.DataFrame, legend: str, metadata: list = None, normalize: bool = False, **kwargs): dimension = points.shape[1] # tweak points size for 3D plots marker_size = 8 if dimension == 3: marker_size = 4 # if indicated, perform normalization if normalize: points = (points - points.min()) / (points.max() - points.min()) marker = dict(color="#236FA4", size=marker_size, symbol="circle", line=dict(color="#236FA4", width=1), opacity=0.8) marker.update(**kwargs) if dimension == 2: trace = go.Scattergl(x=points[0], y=points[1], mode="markers", marker=marker, name=legend, customdata=metadata) elif dimension == 3: trace = go.Scatter3d(x=points[0], y=points[1], z=points[2], mode="markers", marker=marker, name=legend, customdata=metadata) else: dimensions = list() for column in points: dimensions.append( dict( range=[0, 1], label=self.axis_labels[column:column + 1][0] if self.axis_labels[column:column + 1] else None, values=points[column], )) trace = go.Parcoords( line=dict(color="#236FA4"), dimensions=dimensions, name=legend, ) return trace
def main(): dataTime, dataAccuracy = read() dataTime = extract(dataTime, 'meanTime') dataAccuracy = extract(dataAccuracy, 'corrects') df = mkframe(dataAccuracy) col = [] length = 18 cm = plt.get_cmap('gist_rainbow') for i in range(length): col.append(cm(1. * i / length)[:-1]) color = [] for i in col: hexes = [] for j in i: tmp = format(int(str(int(round(j * 255))), 10), 'x') if len(tmp) != 2: tmp = '0' + tmp hexes.append(copy.deepcopy(tmp)) hex = '#' + hexes[0] hex += hexes[1] hex += hexes[2] color.append([1.0, hex]) print((color)) print(df) data = [ go.Parcoords( line=dict(color=df['measure'], colorscale=color), dimensions=list([ dict( range=[-1, 1], # name=df['The number of groups'], label='Task 2', values=df['task2_correlation']), dict( range=[-1, 1], # name=df['The number of groups'], label='Task 3', values=df['task3_correlation']), dict( range=[-1, 1], # name=df['The number of groups'], label='Task 4', values=df['task4_correlation']) ])) ] layout = go.Layout(showlegend=True # plot_bgcolor='#E5E5E5', # paper_bgcolor='#E5E5E5' ) # plt.figure() # parallel_coordinates(data, 'The number of groups') # plt.show() fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig)
def setUp(self): # Construct with mocked _send_restyle_msg method self.figure = go.Figure(data=[ go.Scatter(), go.Bar(), go.Parcoords(dimensions=[{}, {'label': 'dim 2'}, {}]) ]) # Mock out the message method self.figure._send_restyle_msg = MagicMock()
def parallel_coordinate_plot(self, investigate=None, image_name="Plot"): """ Plotly parallel coordinate plot :param investigate: parameter in the legend :param image_name: name of the image :return: """ try: from plotly.offline import plot from plotly import tools import plotly.graph_objs as go except ImportError: print('plotly is not installed') cols = list(self._df) has_category = False if investigate is not None and investigate in self._df.columns: cols.remove(investigate) has_category = True plotly_list = list() for col in cols: data_dict = dict(range=[self._df[col].min(), self._df[col].max()], label=col, values=self._df[col], tickformat='.2f') plotly_list.append(data_dict) data = list() if has_category: data.append( go.Parcoords(line=dict(color=self._df[investigate], colorscale='Viridis', showscale=True, colorbar=dict(title=investigate)), dimensions=plotly_list)) else: data.append(go.Parcoords(dimensions=plotly_list)) # fig = go.Figure(data=data) dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) plot(data, filename=dir + '/' + image_name + '.html')
def main(infile, col_dimensions, categorized, col_color): """ Produce an interactive paracords plotting html Args: infile: str, tabular file col_dimensions: str, comma separated index numbers. For example: "3,4,5" col_color: str, index number """ df = pd.read_csv(infile, sep='\t', parse_dates=True) dimensions = [] col_dimensions = [int(x) - 1 for x in col_dimensions.split(',')] for col in col_dimensions: values = df[df.columns[col]] if categorized == 'boolfalse' and all(type(e) is int for e in values): dimensions.append( dict(values=values, tickformat=",.2r", label=df.columns[col])) elif categorized == 'boolfalse' and all( type(e) is float for e in values): dimensions.append( dict(values=values, tickformat="g", label=df.columns[col])) else: unique_values = list(set(values)) unique_values.sort() dimensions.append( dict(range=[0, len(unique_values) - 1], tickvals=list(range(len(unique_values))), ticktext=[str(e) for e in unique_values], values=list(map(lambda e: unique_values.index(e), values)), label=df.columns[col])) col_color = int(col_color) - 1 colors = df[df.columns[col_color]] if all(type(e) is int for e in colors): tickformat = ",.2r" elif all(type(e) is float for e in colors): tickformat = "g" else: sys.exit( "Error: the column for coloring must contain all numerical values!" ) dimensions.append( dict(values=colors, tickformat=tickformat, label=df.columns[col_color])) line = dict(color=colors, colorscale='Jet', showscale=True, reversescale=True) data = [go.Parcoords(line=line, dimensions=dimensions)] plotly.offline.plot(data, filename="output.html", auto_open=False)
def update_linesPlot(ats, selecteddata): if target in numericals: fig = { 'data': [ go.Parcoords(line=dict(color=df[target], colorscale='Viridis', showscale=True), dimensions=list([ dict(range=[min(df[i]), max(df[i])], label=i, values=df[i]) for i in ats ])) ] } if target not in numericals: fig = { 'data': [ go.Parcoords(line=dict( color=df["numerical_target"], colorbar=dict( title=target, titleside='top', tickmode='array', tickvals=[numtar[i] for i in set(df[target])], ticktext=list(set(df[target])), ticks='outside'), colorscale='Viridis', showscale=True), dimensions=list([ dict(range=[min(df[i]), max(df[i])], label=i, values=df[i]) for i in ats ])) ] } return fig
def prepare_parcoords(): data = [ go.Parcoords( line=dict(color=df['professor'], # color bar based on Professors # colorscale = 'Cividis', reversescale=True, showscale=False, ), dimensions=list([ dict( label='professor', values=df['professor']), dict( label='lecture', values=df['lecture']), dict( label='participants', values=df['participants']), dict( label='professional_expertise', values=df['professional_expertise']), dict( label='motivation', values=df['motivation']), dict( label='clear_presentation', values=df['clear_presentation']), dict( label='overall_impression', values=df['overall_impression']), ]) ) ] layout = go.Layout( title=go.layout.Title( text='Professor Review Distribution', ), font=dict( family="Arial,Times New Roman,Balto,Courier New,Gravitas One,Old Standard TT", size=16, color='#000000' ), # margin=go.layout.Margin( # t=200, # pad=4 # ), autosize=False, width=1320, height=800 ) # return iplot(data = data,layout = layout) fig = go.Figure(data = data,layout = layout) return fig
def plot(self, class_column, colorscale='RdBu', labels=None, ranges=None): """ Build a parallel coordinates plot. :param class_column: Column of the pandas dataframe expected to be the "class", i.e, for every unique value on this column, one line color. :param colorscale: plotly colorscale (https://plot.ly/python/colorscales/). :param labels: Name of every dimension. :param ranges: Range to be plotted in every dimension. :return: """ if labels is not None: if len(labels) != len(list(self.df)) - 1: raise ValueError("'labels' must be a list of length equal to the number of columns" " of the dataframe minus one.") else: labels = [] for column in list(self.df): labels.append(column) if ranges is not None: if len(ranges) != len(list(self.df)) - 1: raise ValueError("'ranges' must be a list of length equal to the number of columns" " of the dataframe minus one.") else: ranges = [] for column in list(self.df): ranges.append([min(self.df[column]), max(self.df[column])]) dimensions = [] for index, column in enumerate(list(self.df)): if not column == class_column: dimensions.append(dict( range=ranges[index], label=labels[index], values=self.df[column] )) colormap = {k: i for i, k in enumerate(self.df[class_column].unique())} self.data = [ go.Parcoords( line=dict( color = list(map(lambda x: colormap[x], self.df[class_column])), colorscale=colorscale, showscale=True ), dimensions=dimensions ) ] self._fig = go.Figure(data=self.data, layout=self.layout) return self.plotting_method(self._fig)
def __generate_trace(self, objectives: DataFrame, metadata: list = None, legend: str = '', normalize: bool = False, **kwargs): number_of_objectives = objectives.shape[1] if normalize: objectives = (objectives - objectives.min()) / (objectives.max() - objectives.min()) marker = dict(color='rgb(127, 127, 127)', size=3, symbol='x', line=dict(color='rgb(204, 204, 204)', width=1), opacity=0.8) marker.update(**kwargs) if number_of_objectives == 2: trace = go.Scattergl(x=objectives[0], y=objectives[1], mode='markers', marker=marker, name=legend, customdata=metadata) elif number_of_objectives == 3: trace = go.Scatter3d(x=objectives[0], y=objectives[1], z=objectives[2], mode='markers', marker=marker, name=legend, customdata=metadata) else: dimensions = list() for column in objectives: dimensions.append( dict(range=[0, 1], label=self.axis_labels[column:column + 1][0] if self.axis_labels[column:column + 1] else None, values=objectives[column])) trace = go.Parcoords( line=dict(color='blue'), dimensions=dimensions, name=legend, ) return trace
def generate_parallel_coordinates(selected_packages, selected_measures): data_list = [] for package_name in selected_packages: data = lib.get_processed_package(package_name=package_name) data_list.append(data) df = pd.DataFrame(data=data_list) dimensions = [] for measure in selected_measures: measure_value = df[measure] measure_range = [max(measure_value), min(measure_value)] if measure == "dependency_count" or measure == "open_issues_count" else [min(measure_value), max(measure_value)] dimensions.append(dict(range =measure_range, label = find_measure_details_by_name(measure)['label'], values=measure_value, tickvals=np.unique(measure_value).tolist())) palette = get_palette(df.shape[0]) parcoords = go.Parcoords( dimensions = list(dimensions), line = dict(color = df.index, colorscale = palette), tickfont = dict(size=18), labelfont = dict(size=18) ) data = [parcoords] layout = go.Layout( plot_bgcolor='#171b26', paper_bgcolor='#171b26', font_color='#FFF', font_size=18, font_family='"Open Sans", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif', xaxis=dict( showticklabels=False ), yaxis=dict( showticklabels=False ) ) for i, package in enumerate(selected_packages): trace_dummy = go.Scatter( x=[0, 0, 0], # Data is irrelevant since it won't be shown y=[0, 0, 0], name=package, showlegend=True, marker=dict(color=palette[i], size=30) ) data.append(trace_dummy) return {'data': data, 'layout': layout}
def _get_par_coords(self) -> go.Parcoords: config = Config() self.trace: go.Parcoords = go.Parcoords( line=dict( color=config.color_scale[1][1], colorscale=config.color_scale, cmin=0, cmax=1, ), dimensions=[ self._get_dimension_dict(col) for col in self.selected_columns ], ) return self.trace
def parallel_coordinates_plot(x_dict, y_data, y_label, lower_is_better=True): assert (isinstance(x_dict, dict)), 'x_dict should be a dictionary' assert (isinstance(y_data, list)), 'y_data should be a list' if lower_is_better: cmin = np.min(y_data) cmax = np.mean(y_data) + np.std(y_data) else: cmin = np.mean(y_data) - np.std(y_data) cmax = np.max(y_data) dimensionList = [] for key in x_dict: if True in [isinstance(element, str) for element in x_dict[key]]: x_dict[key] = [str(element) for element in x_dict[key]] categories = list(set(x_dict[key])) values = [categories.index(element) for element in x_dict[key]] tickvals = [-0.5] + list(range( 0, len(categories))) + [len(categories) - 0.5] categories = [''] + categories + [''] dimensionList.append( dict(range=[min(tickvals), max(tickvals)], tickvals=tickvals, ticktext=categories, label=key, values=values)) else: dimensionList.append( dict(range=[np.min(x_dict[key]), np.max(x_dict[key])], label=key, values=x_dict[key])) dimensionList.append( dict(range=[np.min(y_data), np.max(y_data)], label=y_label, values=y_data)) f = [ go.Parcoords(line=dict(color=y_data, colorscale='Bluered', reversescale=lower_is_better, showscale=True, cmin=cmin, cmax=cmax), dimensions=list(dimensionList)) ] return f
def plot_trials(spark_trials): data = [ get_result_dict(t) for t in spark_trials.trials if t['result']['status'] == 'ok' and not np.isnan(t['result']['loss']) ] df = pd.DataFrame(data=data) df = add_color_col(df) plotly_data = [ go.Parcoords(line=dict(color=df['color'], colorscale='Jet', showscale=True, reversescale=True, cmin=-4000, cmax=-100), dimensions=get_dimensions(df)) ] displayHTML(plot(plotly_data, output_type='div'))