def plt_tab2(): tab2 = pd.read_csv("D:\\insight_project\\tabs\\refined_tab\\tab1_2.csv", error_bad_lines=False) df2 = tab2 #np.random.seed(1) colors_a = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 2, colortype='rgb') colors_b = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 31407, colortype='rgb') colors_c = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 21000, colortype='rgb') colors_d = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 100, colortype='rgb') a = df2.name b = df2.num_all_re c = df2.num_neg_re d = [round(x, 2) for x in df2.percent] d_v = [round(x * 1) for x in df2.percent] fig = go.Figure(data=[ go.Table(header=dict(values=[ '<b>Business Name</b>', '<b>Total Reviews</b>', '<b>Negative Reviews</b>', '<b>Percentage</b>' ], line_color='white', fill_color='pink', align='center', font=dict(color='black', size=12)), cells=dict(values=[a, b, c, d_v], line_color=[ np.array(colors_a)[0], np.array(colors_b)[b], np.array(colors_c)[c], np.array(colors_d)[d_v] ], fill_color=[ np.array(colors_a)[0], np.array(colors_b)[b], np.array(colors_c)[c], np.array(colors_d)[d_v] ], align='center', font=dict(color='black', size=11))) ]) #fig.show() return fig
def plt_tab4(): df4 = pd.read_csv("D:\\insight_project\\tabs\\refined_tab\\tab1_4.csv", error_bad_lines=False) colors_a = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 2, colortype='rgb') colors_b = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 578, colortype='rgb') colors_c = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 4332, colortype='rgb') colors_d = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 100, colortype='rgb') a = df4.name a_1 = df4.fans b = df4.num_neg_re c = df4.num_all_re d = [round(x, 2) for x in df4.percent] d_v = [round(x * 1) for x in df4.percent] fig = go.Figure(data=[ go.Table(header=dict(values=[ '<b>Fisrt Name</b>', '<b>Fans</b>', '<b>Negative Reviews</b>', '<b>Total Reviews</b>', '<b>Percentage</b>' ], line_color='white', fill_color='pink', align='center', font=dict(color='black', size=12)), cells=dict(values=[a, a_1, b, c, d], line_color=[ np.array(colors_a)[0], np.array(colors_a)[0], np.array(colors_b)[b], np.array(colors_c)[c], np.array(colors_d)[d_v] ], fill_color=[ np.array(colors_a)[0], np.array(colors_a)[0], np.array(colors_b)[b], np.array(colors_c)[c], np.array(colors_d)[d_v] ], align='center', font=dict(color='black', size=11))) ]) #fig.show() return fig
def get_color_palette(num, colors=DEFAULT_PLOTLY_COLORS): """Returns ``num`` of distinct RGB colors. If ``num`` is less than or equal to the length of ``colors``, first ``num`` elements of ``colors`` are returned. Else ``num`` elements of colors are interpolated between the first and the last colors of ``colors``. Parameters ---------- num : `int` Number of colors required. colors : [`str`, `list` [`str`]], default ``DEFAULT_PLOTLY_COLORS`` Which colors to use to build the color palette. This can be a list of RGB colors or a `str` from ``PLOTLY_SCALES``. Returns ------- color_palette: List A list consisting ``num`` of RGB colors. """ validate_colors(colors, colortype="rgb") if len(colors) == 1: return colors * num elif len(colors) >= num: color_palette = colors[0:num] else: color_palette = n_colors( colors[0], colors[-1], num, colortype="rgb") return color_palette
def clf_table_report(self): """This function implements heatmap style pipeline cluster's model evaluation report(Dynamic Table) for classification output report. Parameters ---------- Example ------- .. [Example] https://optimal-flow.readthedocs.io/en/latest/demos.html#pipeline-cluster-model-evaluation-dynamic-table-using-autoviz References ---------- """ df = self.dyna_report colors = n_colors('rgb(49, 130, 189)', 'rgb(239, 243, 255)', 15, colortype='rgb') bins = [-1, 2, 4, 6, 7, 8, 9, 11] bins_latency = [0, 5, 10, 15, 20, 50, 80, 100] labels = [1, 2, 3, 4, 5, 6, 7] fig = go.Figure(data=[ go.Table( header=dict(values=list(df.columns), fill_color='paleturquoise', font=dict(color='black', size=12), align='center'), cells=dict( values=[ df.Dataset, df.Model_Name, df.Best_Parameters, df.Accuracy, df.Precision, df.Recall, df.Latency ], # fill_color='lavender', fill_color=[ 'lavender', 'lavender', 'lavender', np.array(colors)[pd.cut(df.Accuracy.apply( lambda x: x * 10), bins=bins, labels=labels).astype(int)], np.array(colors)[pd.cut(df.Precision.apply( lambda x: x * 10), bins=bins, labels=labels).astype(int)], np.array(colors)[pd.cut( df.Recall.apply(lambda x: x * 10), bins=bins, labels=labels).astype(int)], 'lavender' ], align='left')) # np.array(colors)[pd.cut(df.Latency,bins=bins_latency, labels=labels).astype(int)]], ]) fig.update_layout( title= f'Pipeline Cluster Model Classification Evaluation Report - autoViz <a href="https://www.linkedin.com/in/lei-tony-dong/"> ©Tony Dong</a>', font_size=8) plot(fig) fig.show()
def build_table(uc_switch, val_idx): table = table_array_for('f', 'q') for k, v in results[interval_idx].items(): (f, uc, q) = k if (uc_switch and uc) or (not uc_switch and not uc): table[param['f'].index(f)][param['q'].index( q)] = round(v[val_idx][1], 2) min_val = pow(2, 31) - 1 max_val = 0 for row in table: if min(row) < min_val: min_val = min(row) if max(row) > max_val: max_val = max(row) diff = max_val-min_val cs = n_colors('rgb(0, 255, 0)', 'rgb(255, 0, 0)', int(diff) + 1, colortype='rgb') colors = [] for row in table: c_row = [] for cell in row: c_row.append(cs[int(cell-min_val)]) colors.append(c_row) for idx, row in enumerate(colors): for idx_r, cell in enumerate(row): if(cell == 'rgb(255.00000000000003, -2.842170943040401e-14, 0.0)' or cell == 'rgb(254.99999999999997, 2.842170943040401e-14, 0.0)'): colors[idx][idx_r] = 'rgb(255,0,0)' return make_table('f', 'q', table, colors)
def _plotly_color_map(names: List[str]) -> Mapping[str, str]: """ Private plot helper method for generating colors for similar groups across subplots. Parameters ---------- names: List of levels in a group. Returns ------- Dictionary assigning group names to a color. """ if len(names) > 1: linear_purple_scale = n_colors(lowcolor='rgb(218,183,193)', highcolor='rgb(64,19,98)', n_colors=len(names), colortype='rgb') hex_scale = [ rgb_to_hex(*unlabel_rgb(rgb)) for rgb in linear_purple_scale ] # From https://github.com/plotly/plotly.py/issues/1026 color_generator = cycle(hex_scale) return dict(zip(names, color_generator)) else: return dict(zip(names, ['rgb(64,19,98)']))
def get_ridgeplot_fig(df, distance='total_distance', nvals='all'): clubs, xmin, xmax = utils.get_clubs(df) colors = n_colors('rgb(242, 139, 0)', 'rgb(206, 0, 0)', 12, colortype='rgb') fig = go.Figure() for club, color in zip(clubs, colors): name = utils.club_enum[club] array = df.groupby('club').get_group(club)[distance].values data = utils.get_values(array, nvals) fig.add_trace(go.Violin(x=data, name=name, line_color=color)) fig.update_traces( orientation='h', side='positive', width=3, points=False, ) fig.update_layout( margin=dict(t=30, r=10, b=10, l=10), xaxis_showgrid=True, xaxis_zeroline=False, showlegend=False, xaxis=dict( range=[xmin-10, xmax+20], tickmode='linear', tick0=0, dtick=10, ) ) return fig
def ridge_line(df_act, t_range='day', n=1000): """ https://plotly.com/python/violin/ for one day plot the activity distribution over the day - sample uniform from each interval """ df = activities_dist(df_act.copy(), t_range, n) colors = n_colors('rgb(5, 200, 200)', 'rgb(200, 10, 10)', len(df.columns), colortype='rgb') data = df.values.T fig = go.Figure() i = 0 for data_line, color in zip(data, colors): fig.add_trace( go.Violin(x=data_line, line_color=color, name=df.columns[i])) i += 1 fig.update_traces(orientation='h', side='positive', width=3, points=False) fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False) return fig
def violin_plot(): """Get data for plot, return plot Adds plotly.graph_objects charts for violin plot at initial loading page Returns: (dcc.Graph) """ np.random.seed(1) points = (np.linspace(1, 2, 12)[:, None] * np.random.randn(12, 200) + (np.arange(12) + 2 * np.random.random(12))[:, None]) points2 = np.array([ np.concatenate((point, [points.min(), points.max()])) for point in points ]) colors = n_colors('rgb(32, 32, 41)', 'rgb(190, 155, 137)', 12, colortype='rgb') data = [] for data_line, color in zip(points2, colors): trace = go.Violin(x=data_line, line_color=color, side='positive', width=3, points=False, hoverinfo='skip') data.append(trace) layout = dict(title='u t i l s . p y', xaxis={ 'showgrid': False, 'zeroline': False, 'visible': False, 'fixedrange': True, }, yaxis={ 'showgrid': False, 'zeroline': False, 'visible': False, 'fixedrange': True, }, showlegend=False, margin=dict(l=0, r=0, t=80, b=0)) return dcc.Graph(figure=dict(data=data, layout=layout), id='violin-plot', config={ 'modeBarButtonsToRemove': [ 'zoom2d', 'pan2d', 'select2d', 'lasso2d', 'zoomIn2d', 'zoomOut2d', 'autoScale2d', 'resetScale2d', 'toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian' ], }, style={ 'margin-top': '15vh', 'height': '60vh' })
def code_couleur(tableau, mini, maxi): tab_coul = n_colors('rgb(200, 100, 100)', 'rgb(100, 200, 100)', 100, colortype='rgb') tab_pourcent = [ np.int((v - mini) * 100 / (maxi - mini)) if not np.isnan(v) else 0 for v in tableau ] return np.array(tab_coul)[tab_pourcent]
def plot_table(data_list): from plotly.colors import n_colors color_scales = n_colors('rgb(0, 255, 0)', 'rgb(255, 0, 0)', 100, colortype='rgb') stocks = [f"{x['TICKER']}: {x['STOCK']}" for x in data_list] k9 = [f"{x['K9']:.2f}" for x in data_list] d9 = [f"{x['D9']:.2f}" for x in data_list] closes = [f"{x['CLOSE']:.3f}" for x in data_list] change = [f"{x['CHANGE']:+.3f}" for x in data_list] change_pct = [f"{x['CHANGE%']:+.2f}%" for x in data_list] updated = [x['UPDATED'] for x in data_list] # setup cell colors headers = ['STOCK', 'K9', 'D9', 'CLOSE', 'CHANGE', 'CHANGE%', 'UPDATED'] row_num = len(stocks) col_num = len(headers) odd_even_colors = ('white', 'beige') row_colors = [odd_even_colors[x % 2] for x in range(row_num)] blacks = ['black'] * row_num k9_colors = [color_scales[int(float(k))] for k in k9] chg_colors = [] for x in data_list: chg = x['CHANGE'] if chg < 0: chg_colors.append('#db0000') elif chg > 0: chg_colors.append('#02cf4d') else: chg_colors.append('gray') cell_colors = [ blacks, k9_colors, blacks, blacks, chg_colors, chg_colors, blacks ] fig = go.Figure(data=[ go.Table(columnwidth=[200, 40, 40, 40, 40, 40, 80], header=dict(values=headers, line_color='darkslategray', fill_color='lightskyblue', align='left'), cells=dict(values=[ stocks, k9, d9, closes, change, change_pct, updated ], line_color='darkslategray', fill_color=[row_colors * col_num], font=dict(color=cell_colors), align='left')) ]) fig.update_layout(height=250 + len(data_list) * 25) return fig.to_html(full_html=False, include_plotlyjs='cdn')
def reg_table_report(self): """This function implements heatmap style pipeline cluster's model evaluation report(Dynamic Table) for regression output report. Parameters ---------- Example ------- .. [Example] https://optimal-flow.readthedocs.io/en/latest/demos.html#pipeline-cluster-model-evaluation-dynamic-table-using-autoviz References ---------- """ df = self.dyna_report colors = n_colors('rgb(49, 130, 189)', 'rgb(239, 243, 255)', 15, colortype='rgb') bins = [-1, 2, 4, 6, 7, 8, 9, 11] labels = [1, 2, 3, 4, 5, 6, 7] fig = go.Figure(data=[ go.Table( header=dict(values=list(df.columns), fill_color='paleturquoise', align='left'), cells=dict( values=[ df.Dataset, df.Model_Name, df.Best_Parameters, df.R2, df.MAE, df.MSE, df.RMSE, df.Latency ], # fill_color='lavender', fill_color=[ 'lavender', 'lavender', 'lavender', np.array(colors)[pd.cut(df.R2.apply(lambda x: x * 10), bins=bins, labels=labels).astype(int)], 'lavender', 'lavender', 'lavender', 'lavender' ], align='left')) ]) fig.update_layout( title= f'Pipeline Cluster Model Regression Evaluation Report - autoViz <a href="https://www.linkedin.com/in/lei-tony-dong/"> ©Tony Dong</a>', font_size=8) plot(fig, filename='Pipeline Cluster Model Evaluation Report.html', auto_open=False)
def monthly_distribution(sample_year, months, years, temps, monthly_path): ''' Function to compute the monthly temperature distribution Parameters ---------- sample_year: year of your choice (integer) it is either 2007 or 2008 months : numpy.ndarray (integer) 1-dimensional numpy array with month identifiers temps: numpy.ndarray (integer) temperature (Celsius) of the measurement years: numpy.ndarray (integer) year of the measurement monthly_path: string path where to export the distribution in .html ''' unique_months = np.unique(months) names = [ 'Jan. {y}'.format(y=sample_year), 'Feb. {y}'.format(y=sample_year), 'Mar. {y}'.format(y=sample_year), 'Apr. {y}'.format(y=sample_year), 'May {y}'.format(y=sample_year), 'Jun. {y}'.format(y=sample_year), 'Jul. {y}'.format(y=sample_year), 'Aug. {y}'.format(y=sample_year), 'Sept. {y}'.format(y=sample_year), 'Oct. {y}'.format(y=sample_year), 'Nov. {y}'.format(y=sample_year), 'Dec. {y}'.format(y=sample_year) ] colors = n_colors('rgb(10, 200, 197)', 'rgb(10, 200, 197)', 12, colortype='rgb') fig = go.Figure() for month, color, name in zip(unique_months, colors, names): fig.add_trace( go.Violin(x=temps[((months == month) & (years == sample_year)).nonzero()[0]], line=dict(color=color), orientation='h', side='positive', points=False, name=name)) fig.layout.update( title= 'Distribution of Monthly Temperatures {y} (kernel density estimation plot)' .format(y=sample_year), xaxis=dict(title="Temperature (C°)")) pyo.plot(fig, filename=monthly_path)
def createTable(keyword,username,bio,location,followers,following,isNew): new=[] for i in isNew: if i[0]: new.append(1) else: new.append(0) colors = n_colors('rgb(255, 255, 255)', 'rgb(80, 220, 100)', 2, colortype='rgb') fig = go.Figure(data=[go.Table( columnorder = [1,2,3,4,5,6], columnwidth = [20,30,20,20,20,20], header=dict( values=['<b>username</b>','<b>bio</b>','<b>location</b>','<b>followers</b>','<b>following</b>','<b>is new</b>'], line_color='black', fill_color='white', align='center',font=dict(color='black', size=12) ), cells=dict( values=[username,bio,location,followers,following,isNew], line_color=['black'], fill_color=[np.array(colors)[new]], align='center', font=dict(color='black', size=11) )) ]) filePath = "/home/code/Desktop/twitterscraper/images/tables/{key}.png".format(key=(keyword + '_table')) if (os.path.isfile(filePath)): os.remove(filePath) fig.write_image(filePath,width=800, height=len(username)*120) print(keyword+' table created') # fig = go.Figure(data=[go.Table(header=dict(values=['username','bio','location','followers','following','is new']), # cells=dict(values=[username,bio,location,followers,following,isNew])) # ]) # createTable(['exgoog'],['username','username2'],['bio','bio2'],['location','location2'],['followers','followers2'],['following','following2'],[True,False])
def table_report(self): """This function implements heatmap style pipeline cluster's model evaluation report. Parameters ---------- Example ------- .. [] References ---------- """ colors = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 9, colortype='rgb') df = self.dyna_report fig = go.Figure(data=[ go.Table( header=dict(values=list(df.columns), fill_color='paleturquoise', align='left'), cells=dict( values=[ df.Dataset, df.Model_Name, df.Best_Parameters, df.Accuracy, df.Precision, df.Recall, df.Latency ], # fill_color='lavender', fill_color=[ np.array(colors)[df.Accuracy], np.array(colors)[df.Precision], np.array(colors)[df.Recall] ], align='left')) ]) fig.update_layout( title= f'Pipeline Cluster Model Evaluation Report - autoViz <a href="https://www.linkedin.com/in/lei-tony-dong/"> ©Tony Dong</a>', font_size=8) plot(fig) fig.show()
def individuals_distribution(ids, temps, ind_path): ''' Function to compute the distribution in temperature of each bird Parameters ---------- ids: numpy.ndarray (integer) bird identifiers temps: numpy.ndarray (integer) temperature (Celsius) of the measurement ind_path: string path where to export the distribution in .html ''' unique_ids = np.unique(ids) names = [ "Goose 72364", "Goose 72413", "Goose 72417", "Goose 73053", "Goose 73054", "Goose 79694", "Goose 79698" ] colors = n_colors('rgb(150, 150, 150)', 'rgb(150, 150, 150)', 7, colortype='rgb') fig = go.Figure() for goose, color, name in zip(unique_ids, colors, names): fig.add_trace( go.Violin(x=temps[ids == goose], line=dict(color=color), orientation='h', side='positive', points=False, name=name)) fig.layout.update( title= 'Distribution of Individual Temperatures (kernel density estimation plot)', xaxis=dict(title="Temperature (C°)")) pyo.plot(fig, filename=ind_path)
def coloured_table(tab, name, colours_from, colours_to, MAIN_COLOUR, HEADER_FONT_SIZE, BIG_HEADER_FONT_SIZE): """Стандартная функция для отображения таблицы с выделением градиента по значениям Args: tab (pd.DataFrame): Таблица для отображения name (str): Title colours_from (str, optionsl): Начальный цвет градиента colours_to (str, optional): Конечный цвет градиента. Defaults to 'rgb(255, 255, 255)'. Returns: ОТображаемый объект """ month_names = [ '', 'Январь', 'Февраль', "Март", 'Апрель', 'Май', "Июнь", 'Июль', 'Август', "Сентябрь", 'Октябрь', 'Ноябрь', "Декабрь" ] min_value = tab.drop(columns='Unnamed: 0').min().min() quantity_colours = tab.drop(columns='Unnamed: 0').max().max() - min_value if quantity_colours: colors_c = np.array( n_colors(colours_from, colours_to, quantity_colours, colortype='rgb')) colors_f = np.array( n_colors(colours_to, colours_from, quantity_colours, colortype='rgb')) # Первая колонка всегда белая colors_f[0] = 'rgb(255, 255, 255)' else: # Первая колонка все=гда белая colors_c = np.array(['rgb(255, 255, 255)']) colors_f = np.array(['rgb(255, 255, 255)']) colors_f[0] = 'rgb(255, 255, 255)' color_cells = [ colors_c[tab[c] - min_value - 1] if c != 'Unnamed: 0' else colours_to for c in tab ] color_fonts = [ colors_f[tab[c] - min_value - 1] if c != 'Unnamed: 0' else colours_from for c in tab ] qual_deficit_fig = go.Figure(data=[ go.Table(header=dict( values=[month_names[c] for c in range(len(tab.columns))], line_color='white', fill_color='white', align='center', font=dict(color=MAIN_COLOUR, size=HEADER_FONT_SIZE)), cells=dict(values=[tab[c] for c in tab], line_color=color_cells, fill_color=color_cells, align='center', font=dict(color=color_fonts, size=TABLE_FONT_SIZE), height=CELL_HEIGHT)) ], layout=dict(title=dict( text=name, font=dict(color=MAIN_COLOUR, size=BIG_HEADER_FONT_SIZE)), height=500)) return qual_deficit_fig
def _bullet(df, markers, measures, ranges, subtitles, titles, orientation, range_colors, measure_colors, horizontal_spacing, vertical_spacing, scatter_options, layout_options): num_of_lanes = len(df) num_of_rows = num_of_lanes if orientation == 'h' else 1 num_of_cols = 1 if orientation == 'h' else num_of_lanes if not horizontal_spacing: horizontal_spacing = 1. / num_of_lanes if not vertical_spacing: vertical_spacing = 1. / num_of_lanes fig = plotly.tools.make_subplots(num_of_rows, num_of_cols, print_grid=False, horizontal_spacing=horizontal_spacing, vertical_spacing=vertical_spacing) # layout fig['layout'].update( dict(shapes=[]), title='Bullet Chart', height=600, width=1000, showlegend=False, barmode='stack', annotations=[], margin=dict(l=120 if orientation == 'h' else 80), ) # update layout fig['layout'].update(layout_options) if orientation == 'h': width_axis = 'yaxis' length_axis = 'xaxis' else: width_axis = 'xaxis' length_axis = 'yaxis' for key in fig['layout'].keys(): if 'axis' in key: fig['layout'][key]['showgrid'] = False fig['layout'][key]['zeroline'] = False if length_axis in key: fig['layout'][key]['tickwidth'] = 1 if width_axis in key: fig['layout'][key]['showticklabels'] = False fig['layout'][key]['range'] = [0, 1] # narrow domain if 1 bar if num_of_lanes <= 1: fig['layout'][width_axis + '1']['domain'] = [0.4, 0.6] if not range_colors: range_colors = ['rgb(200, 200, 200)', 'rgb(245, 245, 245)'] if not measure_colors: measure_colors = ['rgb(31, 119, 180)', 'rgb(176, 196, 221)'] for row in range(num_of_lanes): # ranges bars for idx in range(len(df.iloc[row]['ranges'])): inter_colors = colors.n_colors(range_colors[0], range_colors[1], len(df.iloc[row]['ranges']), 'rgb') x = ([sorted(df.iloc[row]['ranges'])[-1 - idx]] if orientation == 'h' else [0]) y = ([0] if orientation == 'h' else [sorted(df.iloc[row]['ranges'])[-1 - idx]]) bar = go.Bar(x=x, y=y, marker=dict(color=inter_colors[-1 - idx]), name='ranges', hoverinfo='x' if orientation == 'h' else 'y', orientation=orientation, width=2, base=0, xaxis='x{}'.format(row + 1), yaxis='y{}'.format(row + 1)) fig['data'].append(bar) # measures bars for idx in range(len(df.iloc[row]['measures'])): inter_colors = colors.n_colors(measure_colors[0], measure_colors[1], len(df.iloc[row]['measures']), 'rgb') x = ([sorted(df.iloc[row]['measures'])[-1 - idx]] if orientation == 'h' else [0.5]) y = ([0.5] if orientation == 'h' else [sorted(df.iloc[row]['measures'])[-1 - idx]]) bar = go.Bar(x=x, y=y, marker=dict(color=inter_colors[-1 - idx]), name='measures', hoverinfo='x' if orientation == 'h' else 'y', orientation=orientation, width=0.4, base=0, xaxis='x{}'.format(row + 1), yaxis='y{}'.format(row + 1)) fig['data'].append(bar) # markers x = df.iloc[row]['markers'] if orientation == 'h' else [0.5] y = [0.5] if orientation == 'h' else df.iloc[row]['markers'] markers = go.Scatter(x=x, y=y, name='markers', hoverinfo='x' if orientation == 'h' else 'y', xaxis='x{}'.format(row + 1), yaxis='y{}'.format(row + 1), **scatter_options) fig['data'].append(markers) # titles and subtitles title = df.iloc[row]['titles'] if 'subtitles' in df: subtitle = '<br>{}'.format(df.iloc[row]['subtitles']) else: subtitle = '' label = '<b>{}</b>'.format(title) + subtitle annot = utils.annotation_dict_for_label( label, (num_of_lanes - row if orientation == 'h' else row + 1), num_of_lanes, vertical_spacing if orientation == 'h' else horizontal_spacing, 'row' if orientation == 'h' else 'col', True if orientation == 'h' else False, False) fig['layout']['annotations'].append(annot) return fig
def materiality_table_FEATURES_plotly(self, short = '', variable = 'mean', norm = '', std = True, n_areas = 2, selection = 'all', type = 'Feat'): cat1 , cat2, cat3, catG = 0, 1, 2, 3 if type == 'Feat': df = self.priorities_feats_df else: df = self.priorities_needs_df if norm == True: norm = '_norm' if short != '': df = df.loc[short] c1 = categories[cat1] + '_' + variable + norm c2 = categories[cat2] + '_' + variable + norm c3 = categories[cat3] + '_' + variable + norm cG = categories[catG] + '_' + variable + norm bord_low = min(df[c1].min(), df[c2].min(), df[c3].min(), df[cG].min()) bord_hig = max(df[c1].max(), df[c2].max(), df[c3].max(), df[cG].min()) d = (bord_hig-bord_low)/10 bord_low = bord_low - d bord_hig = bord_hig + d if selection != 'all' : df = df.iloc[selection] df = df.sort_values(by = cG ) hoverinfo = {3: 'Must have', 2: 'Key to discuss', 1: 'Potential added value', 0: 'To exclude'} for c in [cG, c1, c2, c3]: df[c] = df[c].map(lambda val: int(round((val - df[c].min()*0.9)*3/(df[c].max()*1.1 - df[c].min()*0.9))) ) df[c + 'hi'] = df[c].map(lambda val: hoverinfo[val]) colors = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 9, colortype='rgb') fig = ff.create_annotated_heatmap(df[[cG, c1, c2, c3]].values, #labels=dict(x=df_.index, y=[cG, c1, c2, c3], color="w"), x=[categories[3], categories[0], categories[1], categories[2]], y=df.index.array, hovertemplate = "%{y}:<br>%{text}", #hoverlabel=dict(font=dict(family='sans-serif', size=10)), text = df[[cG + 'hi', c1+ 'hi', c2+ 'hi', c3+ 'hi']].values, annotation_text=df[[cG + 'hi', c1+ 'hi', c2+ 'hi', c3+ 'hi']].values, colorscale='YlGnBu',#px.colors.diverging.Portland,#px.colors.sequential.Viridis, #reversescale=True, xgap = 5, ygap = 5, ) fig.update_layout( xaxis=dict(showgrid=False), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', height = 38 * df.shape[0] + 60, font=dict(size=10,) ) fig.add_traces(self.add_score_bar(df, cat = 0)) fig.add_traces(self.add_score_bar(df, cat = 1)) fig.add_traces(self.add_score_bar(df, cat = 2)) #fig.add_traces(self.add_score_bar(df, cat = 1)) # initialize xaxis2 and yaxis2 fig['layout']['xaxis2'] = {} fig['layout']['yaxis2'] = {} # Edit layout for subplots fig.layout.xaxis.update({'domain': [0, 0.64]}) fig.layout.xaxis2.update({'domain': [0.65, 1.]}) fig.layout.yaxis2.update({'anchor': 'x2', 'visible': False}) fig.layout.margin.update({'t':40, 'b':20}) return fig
tab = trade_df['netCash'].values.tolist() tab = np.array(tab) # print(np.min(tab)) redgreen = ['#df0101', '#f5f6ce', '#31b404'] fin_cmap, fin_cs = colorscale_from_list(redgreen, 'fin_cmap') fin_asymm_cs = asymmetric_colorscale(tab, fin_cmap, ref_point=0.0, step=0.05) print(fin_asymm_cs) # color scale a = [4, 11, 0, 32] blues = n_colors('rgb(200, 200, 255)', 'rgb(0, 0, 200)', max(a) + 1, colortype='rgb') print(blues) print([np.array(blues)[a]]) ''' for col in cols_to_show: if col!='': ''' print(trade_df[cols_to_show].values.T) trace = dict( type='table', columnwidth=[20] + [50] + [50] + [20] + [20] + [20] + [20] + [20], header=dict(height=50,
def create_evloution_table(category, algs, slider_val): dev_func = np.std mean_func = np.mean alg_legend = " ".join([token.capitalize() for token in algs[0].split("_")[:2]]) category_1, category_2 = [ val.strip().upper() for val in re.sub("_", " ", category).split("vs") ] title_category = " ".join([category_1.capitalize(), "Vs.", category_2.capitalize()]) if len(algs) == 1: return html.H4( f"No additional noise visualization data in Db found for {title_category} and {alg_legend}" ) list_w_results = [] for alg in algs: res = get_res_from_db(alg, "entropy", category_1, category_2) if res is None: return html.H4( f"No additional noise visualization data in Db found for {title_category} and {alg_legend}" ) list_w_results.append( create_evolution_table_stats(res, mean_func, dev_func, slider_val) ) list_w_results = list(map(list, zip(*list_w_results))) noise_var = [0.1, 0.2, 0.3, 0.4, 0.6] colors = n_colors("rgb(172, 193, 198)", "rgb(2, 52, 81)", 5, colortype="rgb") table_to_vis = [noise_var] + [val for val in list_w_results] slider_val -= 1 fig = go.Figure( data=[ go.Table( header=dict( values=["<b>Noise Variance</b>", "<b>0</b>"] + [ f"<b>{int(i * 200 / (slider_val))}</b>" for i in range(1, slider_val + 1) ], font_size=13, align="center", height=40, ), cells=dict( values=table_to_vis, fill_color=[ np.array(colors)[np.argsort(np.argsort(val))] for val in table_to_vis ], align="center", font_size=13, height=40, ), ) ] ) fig.update_layout( height=500, width=1000, title_text=f"{alg_legend} Algorithm with Respect to Different Additive Noise", ) fig.layout.template = "plotly_dark" return dcc.Graph(figure=fig)
import numpy as np import plotly.colors as pc import plotly.graph_objects as go np.random.seed(1) data = (np.linspace(1, 2, 12)[:, np.newaxis] * np.random.randn(12, 200) + (np.arange(12) + 2 * np.random.random(12))[:, np.newaxis]) colors = pc.n_colors('rgb(5, 200, 200)', 'rgb(200, 10, 10)', 12, colortype='rgb') fig = go.Figure() for data_line, color in zip(data, colors): fig.add_trace(go.Violin(x=data_line, line_color=color)) fig.update_traces(orientation='h', side='positive', width=3, points=False) fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False) fig.show()
values_honest_borda = list(mas_assignment_1.outcome_borda.values()) keys_ascii_honest_plurality = util.number_to_ascii(keys_honest_plurality) keys_ascii_honest_voting_for_two = util.number_to_ascii(keys_honest_voting_for_two) keys_ascii_honest_antiplurality = util.number_to_ascii(keys_honest_antiplurality) keys_ascii_honest_borda = util.number_to_ascii(keys_honest_borda) text_honest_plurality = util.join_strings_for_graph(keys_honest_plurality,keys_ascii_honest_plurality,values_honest_plurality) text_honest_voting_for_two = util.join_strings_for_graph(keys_honest_voting_for_two,keys_ascii_honest_voting_for_two,values_honest_voting_for_two) text_honest_antiplurality = util.join_strings_for_graph(keys_honest_antiplurality,keys_ascii_honest_antiplurality,values_honest_antiplurality) text_honest_borda = util.join_strings_for_graph(keys_honest_borda,keys_ascii_honest_borda,values_honest_borda) #----------Outcome of honest voting for all schemes------------ colors = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', max(values_honest_borda)+1, colortype='rgb') fig_outcome = go.Figure(data=[go.Table( header=dict( values=['<b>Plurality<b>','<b>Voting for two<b>', '<b>Antiplurality<b>', '<b>Borda<b>'], line_color='white', fill_color='white', align='center',font=dict(color='black', size=12) ), cells=dict( values=[text_honest_plurality, text_honest_voting_for_two, text_honest_antiplurality, text_honest_borda], line_color=[np.array(colors)[values_honest_plurality],np.array(colors)[values_honest_voting_for_two],np.array(colors)[values_honest_antiplurality], np.array(colors)[values_honest_borda]], fill_color=[np.array(colors)[values_honest_plurality],np.array(colors)[values_honest_voting_for_two],np.array(colors)[values_honest_antiplurality], np.array(colors)[values_honest_borda]], align='center', font=dict(color='black', size=12) )) ]) fig_outcome.update_layout(
def scatterplot_theme(dataframe, headers, diag, size, height, width, title, index, index_vals, endpts, colormap, colormap_type, **kwargs): """ Refer to FigureFactory.create_scatterplotmatrix() for docstring Returns fig for scatterplotmatrix with both index and colormap picked """ # Check if index is made of string values if isinstance(index_vals[0], str): unique_index_vals = [] for name in index_vals: if name not in unique_index_vals: unique_index_vals.append(name) n_colors_len = len(unique_index_vals) # Convert colormap to list of n RGB tuples if colormap_type == 'seq': foo = clrs.color_parser(colormap, clrs.unlabel_rgb) foo = clrs.n_colors(foo[0], foo[1], n_colors_len) theme = clrs.color_parser(foo, clrs.label_rgb) if colormap_type == 'cat': # leave list of colors the same way theme = colormap dim = len(dataframe) fig = make_subplots(rows=dim, cols=dim, print_grid=False) trace_list = [] legend_param = 0 # Work over all permutations of list pairs for listy in dataframe: for listx in dataframe: # create a dictionary for index_vals unique_index_vals = {} for name in index_vals: if name not in unique_index_vals: unique_index_vals[name] = [] c_indx = 0 # color index # Fill all the rest of the names into the dictionary for name in sorted(unique_index_vals.keys()): new_listx = [] new_listy = [] for j in range(len(index_vals)): if index_vals[j] == name: new_listx.append(listx[j]) new_listy.append(listy[j]) # Generate trace with VISIBLE icon if legend_param == 1: if (listx == listy) and (diag == 'histogram'): trace = graph_objs.Histogram( x=new_listx, marker=dict( color=theme[c_indx]), showlegend=True ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=new_listx, name=None, marker=dict( color=theme[c_indx]), showlegend=True ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size kwargs['marker']['color'] = theme[c_indx] trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=name, showlegend=True, **kwargs ) else: trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=name, marker=dict( size=size, color=theme[c_indx]), showlegend=True, **kwargs ) # Generate trace with INVISIBLE icon else: if (listx == listy) and (diag == 'histogram'): trace = graph_objs.Histogram( x=new_listx, marker=dict( color=theme[c_indx]), showlegend=False ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=new_listx, name=None, marker=dict( color=theme[c_indx]), showlegend=False ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size kwargs['marker']['color'] = theme[c_indx] trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=name, showlegend=False, **kwargs ) else: trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=name, marker=dict( size=size, color=theme[c_indx]), showlegend=False, **kwargs ) # Push the trace into dictionary unique_index_vals[name] = trace if c_indx >= (len(theme) - 1): c_indx = -1 c_indx += 1 trace_list.append(unique_index_vals) legend_param += 1 trace_index = 0 indices = range(1, dim + 1) for y_index in indices: for x_index in indices: for name in sorted(trace_list[trace_index].keys()): fig.append_trace( trace_list[trace_index][name], y_index, x_index) trace_index += 1 # Insert headers into the figure for j in range(dim): xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j) fig['layout'][xaxis_key].update(title=headers[j]) for j in range(dim): yaxis_key = 'yaxis{}'.format(1 + (dim * j)) fig['layout'][yaxis_key].update(title=headers[j]) hide_tick_labels_from_box_subplots(fig) if diag == 'histogram': fig['layout'].update( height=height, width=width, title=title, showlegend=True, barmode='stack') return fig elif diag == 'box': fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig else: fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig else: if endpts: intervals = utils.endpts_to_intervals(endpts) # Convert colormap to list of n RGB tuples if colormap_type == 'seq': foo = clrs.color_parser(colormap, clrs.unlabel_rgb) foo = clrs.n_colors(foo[0], foo[1], len(intervals)) theme = clrs.color_parser(foo, clrs.label_rgb) if colormap_type == 'cat': # leave list of colors the same way theme = colormap dim = len(dataframe) fig = make_subplots(rows=dim, cols=dim, print_grid=False) trace_list = [] legend_param = 0 # Work over all permutations of list pairs for listy in dataframe: for listx in dataframe: interval_labels = {} for interval in intervals: interval_labels[str(interval)] = [] c_indx = 0 # color index # Fill all the rest of the names into the dictionary for interval in intervals: new_listx = [] new_listy = [] for j in range(len(index_vals)): if interval[0] < index_vals[j] <= interval[1]: new_listx.append(listx[j]) new_listy.append(listy[j]) # Generate trace with VISIBLE icon if legend_param == 1: if (listx == listy) and (diag == 'histogram'): trace = graph_objs.Histogram( x=new_listx, marker=dict( color=theme[c_indx]), showlegend=True ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=new_listx, name=None, marker=dict( color=theme[c_indx]), showlegend=True ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size (kwargs['marker'] ['color']) = theme[c_indx] trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=str(interval), showlegend=True, **kwargs ) else: trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=str(interval), marker=dict( size=size, color=theme[c_indx]), showlegend=True, **kwargs ) # Generate trace with INVISIBLE icon else: if (listx == listy) and (diag == 'histogram'): trace = graph_objs.Histogram( x=new_listx, marker=dict( color=theme[c_indx]), showlegend=False ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=new_listx, name=None, marker=dict( color=theme[c_indx]), showlegend=False ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size (kwargs['marker'] ['color']) = theme[c_indx] trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=str(interval), showlegend=False, **kwargs ) else: trace = graph_objs.Scatter( x=new_listx, y=new_listy, mode='markers', name=str(interval), marker=dict( size=size, color=theme[c_indx]), showlegend=False, **kwargs ) # Push the trace into dictionary interval_labels[str(interval)] = trace if c_indx >= (len(theme) - 1): c_indx = -1 c_indx += 1 trace_list.append(interval_labels) legend_param += 1 trace_index = 0 indices = range(1, dim + 1) for y_index in indices: for x_index in indices: for interval in intervals: fig.append_trace( trace_list[trace_index][str(interval)], y_index, x_index) trace_index += 1 # Insert headers into the figure for j in range(dim): xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j) fig['layout'][xaxis_key].update(title=headers[j]) for j in range(dim): yaxis_key = 'yaxis{}'.format(1 + (dim * j)) fig['layout'][yaxis_key].update(title=headers[j]) hide_tick_labels_from_box_subplots(fig) if diag == 'histogram': fig['layout'].update( height=height, width=width, title=title, showlegend=True, barmode='stack') return fig elif diag == 'box': fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig else: fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig else: theme = colormap # add a copy of rgb color to theme if it contains one color if len(theme) <= 1: theme.append(theme[0]) color = [] for incr in range(len(theme)): color.append([1. / (len(theme) - 1) * incr, theme[incr]]) dim = len(dataframe) fig = make_subplots(rows=dim, cols=dim, print_grid=False) trace_list = [] legend_param = 0 # Run through all permutations of list pairs for listy in dataframe: for listx in dataframe: # Generate trace with VISIBLE icon if legend_param == 1: if (listx == listy) and (diag == 'histogram'): trace = graph_objs.Histogram( x=listx, marker=dict( color=theme[0]), showlegend=False ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=listx, marker=dict( color=theme[0]), showlegend=False ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size kwargs['marker']['color'] = index_vals kwargs['marker']['colorscale'] = color kwargs['marker']['showscale'] = True trace = graph_objs.Scatter( x=listx, y=listy, mode='markers', showlegend=False, **kwargs ) else: trace = graph_objs.Scatter( x=listx, y=listy, mode='markers', marker=dict( size=size, color=index_vals, colorscale=color, showscale=True), showlegend=False, **kwargs ) # Generate trace with INVISIBLE icon else: if (listx == listy) and (diag == 'histogram'): trace = graph_objs.Histogram( x=listx, marker=dict( color=theme[0]), showlegend=False ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=listx, marker=dict( color=theme[0]), showlegend=False ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size kwargs['marker']['color'] = index_vals kwargs['marker']['colorscale'] = color kwargs['marker']['showscale'] = False trace = graph_objs.Scatter( x=listx, y=listy, mode='markers', showlegend=False, **kwargs ) else: trace = graph_objs.Scatter( x=listx, y=listy, mode='markers', marker=dict( size=size, color=index_vals, colorscale=color, showscale=False), showlegend=False, **kwargs ) # Push the trace into list trace_list.append(trace) legend_param += 1 trace_index = 0 indices = range(1, dim + 1) for y_index in indices: for x_index in indices: fig.append_trace(trace_list[trace_index], y_index, x_index) trace_index += 1 # Insert headers into the figure for j in range(dim): xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j) fig['layout'][xaxis_key].update(title=headers[j]) for j in range(dim): yaxis_key = 'yaxis{}'.format(1 + (dim * j)) fig['layout'][yaxis_key].update(title=headers[j]) hide_tick_labels_from_box_subplots(fig) if diag == 'histogram': fig['layout'].update( height=height, width=width, title=title, showlegend=True, barmode='stack') return fig elif diag == 'box': fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig else: fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig
def _bullet( df, markers, measures, ranges, subtitles, titles, orientation, range_colors, measure_colors, horizontal_spacing, vertical_spacing, scatter_options, layout_options, ): num_of_lanes = len(df) num_of_rows = num_of_lanes if orientation == "h" else 1 num_of_cols = 1 if orientation == "h" else num_of_lanes if not horizontal_spacing: horizontal_spacing = 1.0 / num_of_lanes if not vertical_spacing: vertical_spacing = 1.0 / num_of_lanes fig = plotly.subplots.make_subplots( num_of_rows, num_of_cols, print_grid=False, horizontal_spacing=horizontal_spacing, vertical_spacing=vertical_spacing, ) # layout fig["layout"].update( dict(shapes=[]), title="Bullet Chart", height=600, width=1000, showlegend=False, barmode="stack", annotations=[], margin=dict(l=120 if orientation == "h" else 80), ) # update layout fig["layout"].update(layout_options) if orientation == "h": width_axis = "yaxis" length_axis = "xaxis" else: width_axis = "xaxis" length_axis = "yaxis" for key in fig["layout"]: if "xaxis" in key or "yaxis" in key: fig["layout"][key]["showgrid"] = False fig["layout"][key]["zeroline"] = False if length_axis in key: fig["layout"][key]["tickwidth"] = 1 if width_axis in key: fig["layout"][key]["showticklabels"] = False fig["layout"][key]["range"] = [0, 1] # narrow domain if 1 bar if num_of_lanes <= 1: fig["layout"][width_axis + "1"]["domain"] = [0.4, 0.6] if not range_colors: range_colors = ["rgb(200, 200, 200)", "rgb(245, 245, 245)"] if not measure_colors: measure_colors = ["rgb(31, 119, 180)", "rgb(176, 196, 221)"] for row in range(num_of_lanes): # ranges bars for idx in range(len(df.iloc[row]["ranges"])): inter_colors = clrs.n_colors(range_colors[0], range_colors[1], len(df.iloc[row]["ranges"]), "rgb") x = ([sorted(df.iloc[row]["ranges"])[-1 - idx]] if orientation == "h" else [0]) y = ([0] if orientation == "h" else [sorted(df.iloc[row]["ranges"])[-1 - idx]]) bar = go.Bar( x=x, y=y, marker=dict(color=inter_colors[-1 - idx]), name="ranges", hoverinfo="x" if orientation == "h" else "y", orientation=orientation, width=2, base=0, xaxis="x{}".format(row + 1), yaxis="y{}".format(row + 1), ) fig.add_trace(bar) # measures bars for idx in range(len(df.iloc[row]["measures"])): inter_colors = clrs.n_colors( measure_colors[0], measure_colors[1], len(df.iloc[row]["measures"]), "rgb", ) x = ([sorted(df.iloc[row]["measures"])[-1 - idx]] if orientation == "h" else [0.5]) y = ([0.5] if orientation == "h" else [sorted(df.iloc[row]["measures"])[-1 - idx]]) bar = go.Bar( x=x, y=y, marker=dict(color=inter_colors[-1 - idx]), name="measures", hoverinfo="x" if orientation == "h" else "y", orientation=orientation, width=0.4, base=0, xaxis="x{}".format(row + 1), yaxis="y{}".format(row + 1), ) fig.add_trace(bar) # markers x = df.iloc[row]["markers"] if orientation == "h" else [0.5] y = [0.5] if orientation == "h" else df.iloc[row]["markers"] markers = go.Scatter(x=x, y=y, name="markers", hoverinfo="x" if orientation == "h" else "y", xaxis="x{}".format(row + 1), yaxis="y{}".format(row + 1), **scatter_options) fig.add_trace(markers) # titles and subtitles title = df.iloc[row]["titles"] if "subtitles" in df: subtitle = "<br>{}".format(df.iloc[row]["subtitles"]) else: subtitle = "" label = "<b>{}</b>".format(title) + subtitle annot = utils.annotation_dict_for_label( label, (num_of_lanes - row if orientation == "h" else row + 1), num_of_lanes, vertical_spacing if orientation == "h" else horizontal_spacing, "row" if orientation == "h" else "col", True if orientation == "h" else False, False, ) fig["layout"]["annotations"] += (annot, ) return fig
title_text="Number of songs per year" ) fig.update_layout( xaxis=dict( rangeslider=dict( visible=True ), type="date" ) ) st.write(fig) st.markdown('This Violin chart helps to investigate how the mean music tempo has been changing') value = st.slider("Year range", 1920, 2014, (1920, 2014), 1) colors = n_colors('rgb(135, 251, 44)', 'rgb(75, 144, 22)', value[1]-value[0], colortype='rgb') fig = go.Figure() for data_line, color, year in zip(dist_per_year[(value[0]-1920):(value[1]-1920)], colors, data['year'].unique()[(value[0]-1920):(value[1]-1920)]): fig.add_trace(go.Violin(x=data_line, line_color=color, name=str(year))) fig.update_traces(orientation='h', side='positive', width=3, points=False) fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False) st.write(fig) if select_event == 'The artist': st.markdown("### **Select Artist:**") select_artist = [] select_artist.append(st.selectbox('', sorted(soloists['artists'].unique()))) artist = soloists[soloists['artists'].str.contains(select_artist[0])] st.markdown("### **Summary statistics:**") st.markdown("Here there is aggregated values of artist's songs characteristics") fig = go.Figure(go.Bar( x=artist[['danceability', 'energy', 'instrumentalness', 'speechiness', "liveness"]].mean(),
def plot_heatmap_week(request): # label timeslot = [x for x in range(7, 23)] weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] # data frequency = [[0 for x in range(1, 8)] for y in range(1, 17)] # get all workouts from user if request.user.is_authenticated: query = Training.objects.all().filter(user_name=request.user).exclude( training_time__isnull=True) else: query = Training.objects.all().filter(user_name='test_user').exclude( training_time__isnull=True) # 2d array of days - timeslots timeslots = pd.date_range("07:30", "22:30", freq="60min").time for i in range(len(query)): ind_day = query.values()[i]['training_date'].weekday( ) # index tag first element of query for j in range(len(timeslots)): if query.values()[i]['training_time'] <= timeslots[j]: frequency[j][ind_day] += 1 break # create hover text - time | frequency text = [[0 for x in range(1, 8)] for y in range(1, 13)] for i in range(len(text)): for j in range(len(text[i])): if frequency[i][j] == 0: text[i][j] = '' else: text[i][j] = f'{timeslot[i]}:00 | {frequency[i][j]}' # color of circles range_frequency = range(0, np.max(frequency) + 1) greys = n_colors('rgba(255,255,255)', 'rgb(0,0,0)', np.max(range_frequency) + 1, colortype='rgb') greys[0] = 'rgba(0,0,0,0)' # zero is transparent colorscale = np.array(greys)[range_frequency] # colorscale legend color = [] for i in range(np.max(frequency) + 1): color.append([i / (np.max(frequency) + 1), greys[i]]) color.append([(i + 1) / (np.max(frequency) + 1), greys[i]]) # plot invisible data to get hover data at the right spot # this plots rectangles in the plot, I want circles/ellipses fig = go.Figure() fig.add_trace( go.Heatmap( x=weekdays, y=timeslot, z=frequency, colorscale=color, #px.colors.sequential.Blugrn, text=text, hoverinfo='text', opacity=0, colorbar=dict(tick0=0, dtick=1), name='Frequency')) # legend with categorical data - otherwise the legend will be continuous text2 = [['' for x in range(1, 8)] for y in range(1, 13)] for i in range(1, np.max(frequency) + 1): fig.add_trace( go.Heatmap( x=weekdays, y=timeslot, z=[None for x in range(1, 8)], name=i, colorscale=[ np.array(greys)[range_frequency][i] for x in range(2) ], text=text2, hoverinfo='text', )) fig.update_traces(showlegend=True, showscale=False) fig.update_layout(yaxis_title="Hour of Day", title='Workout Days & Times:', xaxis={'showgrid': False}, yaxis={'showgrid': False}, font=dict(family="Courier New, monospace", )) fig.update_layout({ 'plot_bgcolor': 'rgba(0, 0, 0, 0)', 'paper_bgcolor': 'rgba(0, 0, 0, 0)', }) fig.update_layout(hovermode='x') # plot circles at the right spots to coincide with data for i in range(len(frequency)): for j in range(len(frequency[0])): if frequency[i][j] > 0: fig.add_shape( type="circle", xref="x", yref="y", x0=j - 0.3, y0=timeslot[i] - 0.5, x1=j + 0.3, y1=timeslot[i] + 0.5, line_color=colorscale[frequency[i][j]], fillcolor=colorscale[frequency[i][j]], ) fig.update_traces(hoverlabel=dict(bgcolor="darkslategrey")) fig['layout']['yaxis']['autorange'] = "reversed" fig.update_xaxes(side="top") fig.layout.xaxis.fixedrange = True fig.layout.yaxis.fixedrange = True config = {'displayModeBar': False} fig.update_layout(margin=dict(l=0, r=0)) fig.update_layout(yaxis=dict(tickmode='linear', tick0=8, dtick=2)) plot_div = plot(fig, output_type='div', config=config) return plot_div
from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from plotly.colors import n_colors import numpy as np from inf import app colorsf = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 90, colortype='rgb') colorsd = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 41, colortype='rgb') a = [ "CCSD", "M06-2X-COMB7", "PBE0", "M06-2X-PBE25-OPT1", "M06-2X-COMB14", "TPSS", "M06-2X-OPT6", "M06-2X_S", "M06-2X" ] b = [0, 1.808, 1.818, 1.867, 1.910, 2.043, 2.941, 4.028, 4.028] c = [0, 24.9783, 83.4887, 89.1403, 19.5589, 0, 16.7704, 19.2325, 18.9840] bc = list(map(lambda x: round(x * 10), b)) cc = list(map(lambda x: round(x), c)) c = ["?", 24.9783, 83.4887, 89.1403, 19.5589, "?", 16.7704, 19.2325, 18.9840] hf = ["-", 0.540, 0.250, 0.250, 0.432, "-", 0.510, 0.540, 0.540] fig = go.Figure(data=[ go.Table(header=dict(values=[ '<b>Функционал</b>', '<b>maxNE</b>', '<b>Ferr</b>', '<b>pHF</b>' ], line_color='white',
dtick='M1', color=MAIN_COLOUR, showgrid=True, gridcolor=MAIN_COLOUR2), yaxis=dict(color=MAIN_COLOUR), plot_bgcolor='rgb(255,255,255)')) return fig if __name__ == '__main__': # Initialise the app app = dash.Dash(__name__) MAIN_COLOUR = 'rgb(156, 60, 56)' MAIN_COLOUR2 = n_colors(MAIN_COLOUR, 'rgb(255, 255, 255)', 3, colortype='rgb')[1] BIG_HEADER_FONT_SIZE = 30 HEADER_FONT_SIZE = 18 TABLE_FONT_SIZE = 14 CELL_HEIGHT = 28 MAIN_PARAMETERS_PLUS = 5 MAIN_PARAMETERS_ADDITIONAL_PLUS = 20 HISTOGRAM_BINS_NUM = 12 YEAR = 2021 GUYS_CODES = [11842, 12230, 12455, 33717, 93898]
def _bullet(df, markers, measures, ranges, subtitles, titles, orientation, range_colors, measure_colors, horizontal_spacing, vertical_spacing, scatter_options, layout_options): num_of_lanes = len(df) num_of_rows = num_of_lanes if orientation == 'h' else 1 num_of_cols = 1 if orientation == 'h' else num_of_lanes if not horizontal_spacing: horizontal_spacing = 1./num_of_lanes if not vertical_spacing: vertical_spacing = 1./num_of_lanes fig = plotly.tools.make_subplots( num_of_rows, num_of_cols, print_grid=False, horizontal_spacing=horizontal_spacing, vertical_spacing=vertical_spacing ) # layout fig['layout'].update( dict(shapes=[]), title='Bullet Chart', height=600, width=1000, showlegend=False, barmode='stack', annotations=[], margin=dict(l=120 if orientation == 'h' else 80), ) # update layout fig['layout'].update(layout_options) if orientation == 'h': width_axis = 'yaxis' length_axis = 'xaxis' else: width_axis = 'xaxis' length_axis = 'yaxis' for key in fig['layout']: if 'xaxis' in key or 'yaxis' in key: fig['layout'][key]['showgrid'] = False fig['layout'][key]['zeroline'] = False if length_axis in key: fig['layout'][key]['tickwidth'] = 1 if width_axis in key: fig['layout'][key]['showticklabels'] = False fig['layout'][key]['range'] = [0, 1] # narrow domain if 1 bar if num_of_lanes <= 1: fig['layout'][width_axis + '1']['domain'] = [0.4, 0.6] if not range_colors: range_colors = ['rgb(200, 200, 200)', 'rgb(245, 245, 245)'] if not measure_colors: measure_colors = ['rgb(31, 119, 180)', 'rgb(176, 196, 221)'] for row in range(num_of_lanes): # ranges bars for idx in range(len(df.iloc[row]['ranges'])): inter_colors = colors.n_colors( range_colors[0], range_colors[1], len(df.iloc[row]['ranges']), 'rgb' ) x = ([sorted(df.iloc[row]['ranges'])[-1 - idx]] if orientation == 'h' else [0]) y = ([0] if orientation == 'h' else [sorted(df.iloc[row]['ranges'])[-1 - idx]]) bar = go.Bar( x=x, y=y, marker=dict( color=inter_colors[-1 - idx] ), name='ranges', hoverinfo='x' if orientation == 'h' else 'y', orientation=orientation, width=2, base=0, xaxis='x{}'.format(row + 1), yaxis='y{}'.format(row + 1) ) fig.add_trace(bar) # measures bars for idx in range(len(df.iloc[row]['measures'])): inter_colors = colors.n_colors( measure_colors[0], measure_colors[1], len(df.iloc[row]['measures']), 'rgb' ) x = ([sorted(df.iloc[row]['measures'])[-1 - idx]] if orientation == 'h' else [0.5]) y = ([0.5] if orientation == 'h' else [sorted(df.iloc[row]['measures'])[-1 - idx]]) bar = go.Bar( x=x, y=y, marker=dict( color=inter_colors[-1 - idx] ), name='measures', hoverinfo='x' if orientation == 'h' else 'y', orientation=orientation, width=0.4, base=0, xaxis='x{}'.format(row + 1), yaxis='y{}'.format(row + 1) ) fig.add_trace(bar) # markers x = df.iloc[row]['markers'] if orientation == 'h' else [0.5] y = [0.5] if orientation == 'h' else df.iloc[row]['markers'] markers = go.Scatter( x=x, y=y, name='markers', hoverinfo='x' if orientation == 'h' else 'y', xaxis='x{}'.format(row + 1), yaxis='y{}'.format(row + 1), **scatter_options ) fig.add_trace(markers) # titles and subtitles title = df.iloc[row]['titles'] if 'subtitles' in df: subtitle = '<br>{}'.format(df.iloc[row]['subtitles']) else: subtitle = '' label = '<b>{}</b>'.format(title) + subtitle annot = utils.annotation_dict_for_label( label, (num_of_lanes - row if orientation == 'h' else row + 1), num_of_lanes, vertical_spacing if orientation == 'h' else horizontal_spacing, 'row' if orientation == 'h' else 'col', True if orientation == 'h' else False, False ) fig['layout']['annotations'] += (annot,) return fig
def plot_table_color(col_labels, values, title='', font_size=12): color_list = ['paleturquoise'] light_color = 'rgb(200, 200, 255)' dark_color = 'rgb(150, 100, 200)' for i in range(1, len(values)): vals = values[i] if isinstance(vals[0], np.int64): if max(vals) - min(vals) == 0: color_list.append(light_color) else: colors = np.array( n_colors(light_color, dark_color, max(vals) - min(vals) + 1, colortype='rgb')) color_list.append(colors[vals - min(vals)]) elif isinstance(vals[0], str): time_units = vals[0].split(':') if len(time_units) == 2: vals = [pd.Timedelta('00:' + x).seconds for x in vals] if max(vals) - min(vals) == 0: color_list.append(light_color) else: colors = np.array( n_colors(light_color, dark_color, max(vals) - min(vals) + 1, colortype='rgb')) color_list.append(colors[[(x - min(vals)) for x in vals]]) elif len(time_units) == 3: vals = [pd.Timedelta(x).seconds for x in vals] if max(vals) - min(vals) == 0: color_list.append(light_color) else: colors = np.array( n_colors(light_color, dark_color, max(vals) - min(vals) + 1, colortype='rgb')) color_list.append(colors[[(x - min(vals)) for x in vals]]) else: color_list.append('white') else: color_list.append('white') fig = go.Figure(data=[ go.Table( # columnorder = [1,2,3], # columnwidth = [80,400], header=dict(values=col_labels, line_color='darkslategray', fill_color='royalblue', align=['center', 'center'], font=dict(color='white', size=12), height=40), cells=dict( values=values, line_color='darkslategray', # fill=dict(color=['paleturquoise', 'white']), fill_color=color_list, align=['left', 'center'], font_size=font_size, height=30)) ]) fig.update_layout( title=title, title_x=0.5, font=dict(family="Times New Roman", size=20, color="Black"), ) return fig