def HeatmapByCat2(data,cbarLab,Ylab,SaveFig,dim=[10,10],cbar_ticks=""): fig=None x = list(data.columns) y = list(data.index.values) if cbar_ticks=="": fig = ff.create_annotated_heatmap(data.values,x=x,y=y,colorscale='viridis_r',showscale=True) else: colPalette =[px.colors.sequential.Reds[0]] +px.colors.sequential.Viridis_r fig = ff.create_annotated_heatmap(data.values,x=x,y=y,colorscale=colPalette,\ showscale=True,zmin=-10,zmax=70,colorbar = {'tickvals':cbar_ticks}) #the magic happens here layout = plotly.graph_objs.Layout(xaxis={'type': 'category'}) fig.update_layout(layout,title =cbarLab) return(fig)
def display_results(position_freqs, ranking_names, results_summary, hits, display_graph=True): if display_graph: hits = min(hits, LIMIT_HITS_GRAPH) z = [list(x) for x in zip(*position_freqs)] z_text = z x = ranking_names y = [str(x + 1) for x in range(int(hits))] fig = ff.create_annotated_heatmap( z, x=x, y=y, annotation_text=z_text, colorscale=py.colors.diverging.RdYlGn) fig.update_layout( xaxis_title_text="Rank profile", # xaxis label yaxis_title_text="Position", # yaxis label ) fig.update_yaxes(autorange="reversed") st.plotly_chart(fig) st.write( DataFrame.from_records(results_summary).sort_values(by="mrr", ascending=False))
def heatmap_graph1(level1='SHOES'): df_history['sold_lw'] = df_history['sold_lw'].astype(int) df_hisp = df_history[df_history['level1'] == level1].pivot_table( index=['week'], columns=['year'], values=['sold_lw'], aggfunc=[np.sum], fill_value=0) ##计算环比 df_his_per = df_hisp.pct_change(periods=1) ##数据框+1后取整 df_hisf = df_his_per.apply(lambda x: round(x + 1, 1)) df_hisf = df_hisf.fillna(0) df_hisf.columns = df_history['year'].astype(str).unique().tolist() print(df_hisf.columns) df_hisf['2015'] = [0.0 if str(x) == 'inf' else x for x in df_hisf['2015']] fig = ff.create_annotated_heatmap(z=np.array(df_hisf.T), x=df_hisf.T.columns.tolist(), y=df_hisf.T.index.tolist(), colorscale='Blues') fig.update_layout(width=1560, height=400, showlegend=False, title_text="历年环比-parameter-%s" % level1) return dcc.Graph(id='heatmap1', figure=fig)
def process(self, output_format): if output_format is utils.PNG or output_format is utils.PDF: #Generate Plot Config for interactive heatmap plot_data = ff.create_annotated_heatmap( x=self.x_axis_values, y=self.y_axis_values, z=self.z_axis_values, hovertemplate=self.hover_tool, name=self.graph_name) else: #Generate Plot Config for interactive heatmap plot_data = go.Heatmap(x=self.x_axis_values, y=self.y_axis_values, z=self.z_axis_values, hovertemplate=self.hover_tool, name=self.graph_name) #Generate Plot Layout plot_layout = go.Layout(autosize=True, width=self.plot_width, height=self.plot_height, paper_bgcolor=str(self.bg_color), plot_bgcolor=str(self.plot_color), title=self.plot_title, xaxis=self.x_axis_title, yaxis=self.y_axis_title, margin=go.layout.Margin(l=int(self.left), r=int(self.right), b=int(self.bottom), t=int(self.top), pad=int(self.padding))) return {'data': [plot_data], 'layout': plot_layout}
def update_map(n): y, a_text, z = heatmap_helper() hover = [] for i in range(len(y)): y_elem = y[i] z_elems = z[i] t_elems = a_text[i] tmp = [] for z_elem, t_elem in zip(z_elems, t_elems): tmp.append("VM: {} <br>Operator: {} <br>Tx number: {}".format(str(t_elem), y_elem, str(z_elem))) hover.append(tmp) colorscale = [[0, '#e8dd9b'], [1, 'rgb(79, 129, 102)']] fig = ff.create_annotated_heatmap(z, y=y, annotation_text=a_text, colorscale=colorscale, text=hover, hoverinfo='text', showscale=True) fig.update_layout( xaxis=dict(title='Vending Machines', showgrid=False, title_font=dict(color='rgb(33, 75, 99)', size=18), zeroline=False), yaxis=dict(title='Operators', title_font=dict(color='rgb(33, 75, 99)', size=18), zeroline=False), plot_bgcolor=('white'), paper_bgcolor="#f9f9f9", ) return fig
def corr_missing_plot(df): na_corr = df.isna().corr() x = list(na_corr.columns) y = list(na_corr.index) z = na_corr.to_numpy() mask = np.triu_indices_from(z) z[mask] = np.nan z_text = np.around(z, decimals=2).astype(str) z_text[mask] = "" z_text[z_text == 'nan'] = "" fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, showscale=True, hoverongaps=False) fig.update_layout( title="Correlation between missingness of different variables", yaxis_title="Variable", xaxis_title="Variable", xaxis_gridcolor='white') fig.update_xaxes(side='bottom') fig.update_yaxes(autorange='reversed') fig.show() return fig
def correlations_heatmap(df): '''Returns a heatmap of the correlations between the numerical columns of a dataframe Parameters: ----------- df: pd.DataFrame ''' correlations = df.corr() columns = correlations.columns correlations = correlations.to_numpy().round(decimals=2) fig = ff.create_annotated_heatmap(z=correlations, x=list(columns), y=list(columns), colorscale='Geyser') fig.update_xaxes(ticks='outside', tickson='boundaries', ticklen=20, tickfont={'size': 8}) fig.update_yaxes(ticks='outside', tickson='boundaries', ticklen=20, tickfont={'size': 8}) for i in range(len(fig.layout.annotations)): fig.layout.annotations[i].font.size = 8 fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', margin=dict(l=20, r=20, t=40, b=20)) return fig.to_json()
def _heat_map(df): x = df.columns.values.tolist() y = df.columns.values.tolist() data = df.values.tolist() fig = ff.create_annotated_heatmap(data, x=x, y=y, colorscale='Greys') return fig
def create_heatmap(data, ratings, name, nan_removed): fig = ff.create_annotated_heatmap(z=data, x=list(np.arange(1, len(ratings) + 1)), y=list(ratings.columns.values), annotation_text=nan_removed, font_colors=['black'], colorscale='RdYlGn', showscale=True) fig.update_yaxes(autorange="reversed") fig.update_layout( title=dict(text="Heatmap of {} episodes rating by season".format(name), x=.5, y=1), xaxis=dict(title="Episodes", tickmode='linear', position=1, showgrid=False, zeroline=False, showline=False), yaxis=dict(title="Seasons", showgrid=False, zeroline=False, showline=False), font=dict(family="Courier New, monospace", size=18, color="#7f7f7f"), height=700, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)') return fig
def plotConfusion(matrix, x=(1, 2, 3, 4), y=(1, 2, 3, 4)): # change each element of z to type string for annotations matrixText = [[str(y) for y in x] for x in matrix] # set up figure fig = ff.create_annotated_heatmap(matrix, x=x, y=y, annotation_text=matrixText, colorscale='Viridis') # add title fig.update_layout(title_text='<i><b>Confusion matrix</b></i>') # add custom xaxis title fig.add_annotation(dict(font=dict(color="black", size=17), x=0.5, y=-0.15, showarrow=False, text="Predicted value", xref="paper", yref="paper")) # add custom yaxis title fig.add_annotation(dict(font=dict(color="black", size=17), x=-0.35, y=0.5, showarrow=False, text="Real value", textangle=-90, xref="paper", yref="paper")) # adjust margins to make room for yaxis title fig.update_layout(margin=dict(t=50, l=200)) # add colorbar fig['data'][0]['showscale'] = True fig.show()
def plot_similarity_heatmap(messages, embeddings): corr = np.inner(embeddings, embeddings) layout = go.Layout(xaxis=dict(autorange=True, showgrid=False, ticks='', showticklabels=False), yaxis=dict(autorange=True, showgrid=False, ticks='', showticklabels=False)) # plot = go.Heatmap( # showscale=False, # z=corr, # x=messages, # y=messages) # fig = go.Figure(data=plot, layout=layout) corr_text = np.around( corr, decimals=2) # Only show rounded value (full value on hover) hover = [] for i in range(len(messages)): temp = [] for j in range(len(messages)): temp.append( f"clause {i} and clause {j} have unscaled correlation of {corr_text[i][j]}" ) hover.append(temp) fig = ff.create_annotated_heatmap(corr, annotation_text=corr_text, text=hover, hoverinfo='text') return fig
def visualize(matrix: np.ndarray, normalized_matrix: np.ndarray, **kwargs) -> Figure: # see https://matplotlib.org/faq/usage_faq.html#coding-styles # see https://plotly.com/python/annotated-heatmap/ # see https://plotly.com/python/builtin-colorscales/ annotation_text = [[ f"True Negative: {normalized_matrix[0, 0]:.3%}", f"False Positive: {normalized_matrix[0, 1]:.3%}" ], [ f"False Negative: {normalized_matrix[1, 0]:.3%}", f"True Positive: {normalized_matrix[1, 1]:.3%}" ]] x_axis_text = ["Predicted False", "Predicted True"] y_axis_text = ["False", "True"] fig = ff.create_annotated_heatmap(matrix, x=x_axis_text, y=y_axis_text, annotation_text=annotation_text, colorscale='Plotly3') fig.update_layout({ 'xaxis': { 'title': { 'text': "Predicted" } }, 'yaxis': { 'title': { 'text': "Ground Truth" } }, }) return fig
def demographics_received(path): df = pd.read_csv(path + 'demoR.csv', index_col=0) df = df.fillna(0) colorscale = [[0.0, 'rgb(250,250,250)'], [0.1, 'rgb(10,250,250)'], [0.2, 'rgb(0,250,250)'], [0.3, 'rgb(0,200,250)'], [0.4, 'rgb(0,150,250)'], [0.5, 'rgb(0,100,250)'], [0.6, 'rgb(0,50,250)'], [0.7, 'rgb(0,0,250)'], [0.8, 'rgb(0,0,200)'], [0.9, 'rgb(0,0,100)'], [1.0, 'rgb(0,0,50)']] fig = ff.create_annotated_heatmap(z=df.values.tolist(), x=df.columns.tolist(), y=df.index.tolist()) fig.update_layout(title_text='Heatmap-Earnings', title_x=0.5, title_y=1, height=900, yaxis=dict(type='category', categoryarray=df.index.tolist()), xaxis=dict(type='category', categoryarray=df.columns.tolist()), yaxis_title="Person", font=dict(family="Courier New, monospace", size=18, color="#7f7f7f")) return fig
def update_figure(value): if value is None: return {'data': []} else: input_data = data_utils.get_updated_data_from_df(value, input_data_original) fig = go.Figure(data=ff.create_annotated_heatmap( z=data_utils.normalize_by_row(input_data.loc[value + ['None'], value+ ['None']].values), y=value + ['None'], x=value + ['None'], colorscale='YlOrRd' ), ) fig.update_layout( title="Usage of SDK by apps", xaxis_title="To SDK", yaxis_title="From SDK", font=dict( family="Courier New, monospace", size=16, color="RebeccaPurple" ) ) fig.update_xaxes(side="bottom") fig.update_layout(clickmode='event+select') return fig
def plot_confusion_matrix(ground_truth, predictions, labels, normalize=True, round_decimal=2): """ :param ground_truth: 1dim-iterable :param predictions: 1dim-iterable :param labels: list of strings describing the classes :param normalize: show raw confusion statistics or normalized to sum to 1 :param round_decimal: :return: """ cm = confusion_matrix(ground_truth, predictions) if normalize: cm = cm / cm.sum(axis=1)[:, np.newaxis] cm_text = pd.DataFrame.from_records(cm).round(round_decimal) figure = ff.create_annotated_heatmap(z=cm, x=labels, y=labels, annotation_text=cm_text, showscale=True) return figure
def lh_printfigs(self, orglist, destlist): edges = self.edges reporttitle = 'Linehaul Edge Data' fl = edges[(edges['Origin'].isin(orglist)) & (edges['Destn'].isin(destlist))] bl = edges[(edges['Origin'].isin(destlist)) & (edges['Destn'].isin(orglist))] df = fl.append(bl) data = [ go.Bar( x=df['Origin_Destn']. values, # assign x as the dataframe column 'x' y=df['CurrMonth'].values) ] layout = go.Layout(barmode='stack', title=reporttitle) fig = go.Figure(data=data, layout=layout) annotations = [] for count, i in enumerate(fig.data[0].get('y')): annotations.append( dict(x=fig.data[0].get('x')[count], y=np.round(i, 2) + 2, text=np.round(i, 1), showarrow=False)) fig.layout['annotations'] = annotations heatmaplist = [] for org, dest, areasplit in zip(df['Origin'], df['Destn'], df['AreaSplit']): for area in list(areasplit.keys()): item = [ area.split('-')[0], area.split('-')[1], areasplit.get(area) ] heatmaplist.append(item) heatmapdf = pd.DataFrame(heatmaplist, columns=['OrgArea', 'DestArea', 'Wt']).dropna() heatmappivot = heatmapdf.pivot_table(index='OrgArea', values='Wt', columns='DestArea', aggfunc=pd.np.sum) heatmappivot = heatmappivot.fillna(0.0).T x = list(heatmappivot.columns) y = list(heatmappivot.index) z = heatmappivot.values z_text = np.around(z, decimals=1) heatmapfig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='Viridis') for i in range(len(heatmapfig.layout.annotations)): heatmapfig.layout.annotations[i].font.size = 10 heatmapfig.layout.title = 'Load Table in Mt' heatmapfig.layout.yaxis.title = 'Destination Area' heatmapfig.layout.xaxis.title = 'Origin Area' heatmapfig.layout.xaxis.side = 'bottom' return fig, heatmapfig
def draw_conf_matrix(confusion_matrix: np.ndarray) -> go.Figure: x = [i for i in range(CLASS_NUMBER)] y = x z_text = [[str(y) for y in x] for x in confusion_matrix] fig = ff.create_annotated_heatmap(confusion_matrix, x=x, y=y, annotation_text=z_text, colorscale='Viridis') fig.update_layout(title_text='<i><b>Confusion matrix</b></i>', ) # add custom xaxis title fig.add_annotation(dict(font=dict(color="black", size=14), x=0.5, y=-0.15, showarrow=False, text="Predicted value", xref="paper", yref="paper")) # add custom yaxis title fig.add_annotation(dict(font=dict(color="black", size=14), x=-0.35, y=0.5, showarrow=False, text="Real value", textangle=-90, xref="paper", yref="paper")) # adjust margins to make room for yaxis title fig.update_layout(margin=dict(t=50, l=200)) for i in range(len(fig.layout.annotations)): fig.layout.annotations[i].font.size = 9 # add colorbar fig['data'][0]['showscale'] = True fig.show() return fig
def heat_map(df): """Create a heatmap for the numerical features of the DataFrame. Args: df (DataFrame): Dataframe object Returns: Figure (fig): a plotly figurene """ df_heat = df[[ "SongsPerHour", "SongsPlayed", "Days", "UpPerSong", "DownPerSong" ]] df_heat = df_heat.corr(method="pearson") z = df_heat.values x = df_heat.columns.tolist() x = [__capitalize__(name) for name in x] font_colors = ["white"] colorscale = [[0, "navy"], [1, "plum"]] fig = ff.create_annotated_heatmap( z=z, x=x, y=x, annotation_text=np.around(z, decimals=2), colorscale=colorscale, font_colors=font_colors, ) fig.update_layout( title=go.layout.Title(text="Heat Map | Numerical Features", x=0.5)) return fig
def create_plotly_ff_heatmap_diff(dataframe): # colorscale_heatmap = [[0, 'rgb(0,67,206)'], [0.5, 'rgb(105,41,196)'],[1, 'rgb(162,25,31)']] max, min = dataframe['diff'].max(), dataframe['diff'].min() midpoint = abs(min) / (abs(max) + abs(min)) colorscale_heatmap = [[0, 'rgb(69,137,255)'], [midpoint, 'rgb(255,255,255)'], [1, 'rgb(250,77,86)']] x_list, y_list = create_axis_lists(dataframe) heatmap_array = create_heatmap_diff_array(dataframe) ts0, ts1 = dataframe.columns[1], dataframe.columns[2] heatmap = ff.create_annotated_heatmap(x=x_list, y=y_list, z=heatmap_array, autocolorscale=False, colorscale=colorscale_heatmap, font_colors=['black'], xgap=10, ygap=1, showscale=True) heatmap.update_layout( title=('Temperature changes from ' + ts0), xaxis=dict(title='Column', side='bottom'), yaxis=dict(title='Row', autorange="reversed"), plot_bgcolor='rgba(0,0,0,0)', ) heatmap.data[0].colorbar = dict(title='Temperature Change', titleside='right') return heatmap
def create_plotly_ff_heatmap_abs(dataframe): # colorscale_heatmap = [[0, 'rgb(0,67,206)'], [0.5, 'rgb(105,41,196)'],[1, 'rgb(162,25,31)']] colorscale_heatmap = [[0, 'rgb(69,137,255)'], [1, 'rgb(250,77,86)']] x_list, y_list = create_axis_lists(dataframe) heatmap_array = create_heatmap_array(dataframe) ts = get_timestamp(dataframe) heatmap = ff.create_annotated_heatmap(x=x_list, y=y_list, z=heatmap_array, colorscale=colorscale_heatmap, xgap=10, ygap=1, showscale=True) heatmap.update_layout( title=('Absolute temperature at ' + ts), xaxis=dict(title='Column', color='black', side='bottom'), yaxis=dict(title='Row', autorange="reversed"), plot_bgcolor='rgba(0,0,0,0)', ) heatmap.data[0].colorbar = dict(title='Temperature', titleside='right') return heatmap
def confusionMatrix(model, X_test, y_test): y_pred = model.predict(X_test) tn, fp, fn, tp = metrics.confusion_matrix(y_test, y_pred).ravel() figure = ff.create_annotated_heatmap( x=["Positive", "Negative"], y=["Positive", "Negative"], z=[[0, 0], [0, 0]], xgap=5, ygap=5, annotation_text=[[f'TP: {tp}', f'FP: {fp}'], [f'FN: {fn}', f'TN: {tn}']], colorscale=[[0, 'rgb(255,255,255)'], [1.0, 'rgb(179, 217, 255)']]) figure.layout.update( xaxis={ 'title': 'Actual Values', 'side': 'top', }, yaxis={ 'title': 'Predicted Values', }, margin={ 'l': 50, 't': 50, 'r': 10, }, height=350, width=300, ) return html.Div( children=[html.H6("Confusion Matrix"), dcc.Graph(figure=figure)])
def plot_matrix(self): matrix_data = pd.DataFrame(confusion_matrix(self.y_test, self.y_pred)) matrix_data = matrix_data.astype('float') / matrix_data.sum( axis=1)[:, np.newaxis] * 100 z = np.array(matrix_data).round(2) x = list(matrix_data.columns) y = list(matrix_data.index) # change each element of z to type string for annotations z_text = [[str(y) for y in x] for x in z] # set up figure fig_matrix = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='Viridis') # add title fig_matrix.update_layout( title_text='<i><b>Confusion matrix (%)</b></i>', xaxis=dict(title='Predicted Label'), yaxis=dict(title='True Label')) # adjust margins to make room for yaxis title fig_matrix.update_layout(margin=dict(t=50, l=200)) # add colorbar fig_matrix['data'][0]['showscale'] = True return fig_matrix
def generate_properties_table(self) -> go.Figure: """ Given Series of the properties associated with a hyperoptimization test on a sample, visualizes a table of those properties. """ y_ticklabels = self.properties.index.to_list() fig = ff.create_annotated_heatmap( z=np.expand_dims(np.ones(self.properties.shape), 1), y=y_ticklabels, colorscale='Inferno', zmin=0, zmax=1, annotation_text=np.expand_dims(self.properties.values, 1), showscale=False, **self.heatmap_shared_attrs ) fig.update_layout( **self.heatmap_layout, height=self.height_per_row * len(self.properties) # QUESTION spend the time to make a more cohesive layout system? ) fig.update_layout( width=None ) fig.update_xaxes(visible=False) return fig
def plot_single_pairwise_sensitivity( methods, psen, title='Pairwise Sensitivity', width=900, height=500, ): z_text = np.around(psen, decimals=2) fig = ff.create_annotated_heatmap( z=psen, # Values x=methods, # X-axis labels y=methods, # Y-axis labels annotation_text=z_text, colorscale='RdBu', hoverinfo='z', zmid=.5, ) # Make text size smaller for i in range(len(fig.layout.annotations)): fig.layout.annotations[i].font.size = 10 fig.update_layout(title=title, margin=dict(t=135), height=height, width=width) fig.show()
def getOverallComplianceHeatmap(sensors_with_data, valid_sensed_hours, last_seven_dates, bin_size, min_bins_per_hour, output_path): plot = ff.create_annotated_heatmap( z=sensors_with_data[last_seven_dates].values, x=[date.replace("-", "/") for date in last_seven_dates], y=[ pid + "<br>" + label for pid, label in zip(sensors_with_data["pid"].to_list(), sensors_with_data["label"].to_list()) ], annotation_text=valid_sensed_hours[last_seven_dates].values, hovertemplate= 'Date: %{x}<br>Participant: %{y}<br>Number of sensors with data: %{z}<extra></extra>', colorscale="Viridis", colorbar={ "tick0": 0, "dtick": 1 }, showscale=True) plot.update_layout( title= "Overall compliance heatmap for last seven days.<br>Bin's color shows how many sensors logged at least one row of data for that day.<br>Bin's text shows the valid hours of that day.(A valid hour has at least one row of any sensor in " + str(min_bins_per_hour) + " out of " + str(int(60 / bin_size)) + " bins of " + str(bin_size) + " minutes)") plot["layout"]["xaxis"].update(side="bottom") pio.write_html(plot, file=output_path, auto_open=False, include_plotlyjs="cdn")
def create_heatmap(title_name, z_values, z_text): font_colors = ['black'] aqi_figure = ff.create_annotated_heatmap(z=z_values, text=z_text, annotation_text=z_text, colorscale=color_scale, zmin=0, zmax=500, font_colors=font_colors, xgap=3, ygap=3) for i in range(len(aqi_figure.layout.annotations)): aqi_figure.layout.annotations[i].font.size = 10 # show colorbar aqi_figure['data'][0]['showscale'] = True aqi_figure.update_layout(autosize=True, title=title_name) # aqi_figure.show() aqi_figure.update_layout( font=dict(color="grey"), height=500, # width=1200, showlegend=True, paper_bgcolor='rgba(0,0,0,0)', xaxis=dict(tickmode='linear', tick0=0, dtick=2000)) aqi_figure_json = json.dumps(aqi_figure, cls=plotly.utils.PlotlyJSONEncoder) return aqi_figure_json
def plotly_df_crosstab_heatmap(df: pd.DataFrame, col1: str, col2: str, ttype: str = 'count', title: bool = False, axes_title: bool = False, save: bool = False, filename: str = 'crosstab_heatmap') -> None: '''Docstring of `plotly_df_crosstab_heatmap` Plot contigency table of two given columns with plotly heatmap. Args: df: A pandas DataFrame. col1: Index of the contigency table. col2: Column of the contigency table. ttype: Determines how the contigency table is calculated. 'count': The counts of every combination. 'colper': The percentage of every combination to the sum of every rows. Defaults to 'count'. title: Whether to show the plot title or not. axes_title: Whether to show the axis' title or not. save: Whether to save the plot or not. filename: Save the plot with this name. ''' ct = df_contingency_table(df, col1, col2, ttype=ttype) fig = ff.create_annotated_heatmap(z=ct.values, x=list(ct.columns), y=list(ct.index)) fig['layout']['title'] = title and '{}-{}'.format(ct.index.name, ct.columns.name) fig['layout']['xaxis']['title'] = axes_title and ct.columns.name fig['layout']['yaxis']['title'] = axes_title and ct.index.name fig['layout']['xaxis']['side'] = 'bottom' save and plt.plot(fig, filename=filename+'.html', auto_open=False) plt.iplot(fig)
def Plot_conf_mat(self, colorscale='Jet'): ''' Función para graficar la matriz de confusión como un mapa de calor. Parámetros: self.y_test (array): Array con las observaciones reales. self.y_pred (array): Array con las predicciones. colorscale (str): Escala de color. Return: fig (Figure): Figura. ''' z = confusion_matrix(self.y_test, self.y_pred) x = ['Izquierda', 'Derecha'] y = ['Izquierda', 'Derecha'] z_text = [[str(y) for y in x] for x in z] fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale=colorscale) fig.update_layout(title_text='<i><b>Matriz de confusión</b></i>', xaxis_title='Predicción', yaxis_title='Valor Real') fig.update_layout(margin=dict(t=50, l=200)) fig['data'][0]['showscale'] = True return fig
def update_heatmap (json_data): # load data from intermediate df_filter = pd.read_json(json_data) dh = df_filter.pivot_table(columns= df_filter.index.hour, index= df_filter.index.dayofweek, values = 'totalNumberOfOccupiedParkingSpaces') # plotting hovertemplate = "<b> %{y} %{x} <br><br> %{z} Occupied Parking Spaces" fig = ff.create_annotated_heatmap( y= [calendar.day_name[a] for a in dh.index], x = [datetime.strptime(str(a), "%H").strftime("%I %p") for a in dh.columns], z = dh.astype(int).values, showscale = False, name = '', hovertemplate = hovertemplate, colorscale= [[0, "#caf3ff"], [1, "#2c82ff"]], ) fig['layout'].update( font = dict(size = 10, color = txt_color), plot_bgcolor = bg_color, paper_bgcolor = bg_color, margin=dict(l=80, b=20, t=50, r=20), modebar={"orientation": "v"}, xaxis=dict( side="top", ticks="", ticklen=2, tickcolor="#ffffff" ), yaxis=dict(side="left", ticks="",), hovermode="closest", showlegend=False,) return fig
def kw_plot(top_key): top_n = 5 kws_df = make_kws_df(top_key, top_n=top_n) heat_df = kws_df.groupby("tag").agg(list) vs = heat_df["influence"].values mat = np.zeros( (len(vs), len(vs[0])), ) for i, r in enumerate(vs): for j, v in enumerate(r): mat[i][j] = v sort_ = mat[:, 0].argsort() z = heat_df["influence"].values[sort_].tolist() y = heat_df.index[sort_].to_list() z_text = heat_df["reason"].values[sort_].tolist() fig = ff.create_annotated_heatmap( z, y=y, x=list(range(1, 1 + top_n, 1)), annotation_text=z_text, colorscale="Blues", showscale=True, ) fig.update_layout( template=TEMPLATE, font_family="Arial", width=1280, height=600, ) return fig
def plotly_correlation(self, corr_matrix, plot_filename, labels, plot_title='', vmax=None, vmin=None, plot_numbers=True, colormap='jet'): """plot_correlation, but using plotly""" textElement = [] for row in range(corr_matrix.shape[0]): trow = [] for col in range(corr_matrix.shape[0]): if plot_numbers: trow.append("{:0.2f}".format(corr_matrix[row, col])) else: trow.append('') textElement.append(trow) zauto = True if vmax is not None or vmin is not None: zauto = False convertedCmap = convertCmap(colormap) fig = ff.create_annotated_heatmap(corr_matrix, x=labels, y=labels, colorscale=convertedCmap, showscale=True, zauto=zauto, zmin=vmin, zmax=vmax, annotation_text=textElement) fig.layout['title'] = plot_title offline.plot(fig, filename=plot_filename, auto_open=False)
def create_annotated_heatmap(*args, **kwargs): FigureFactory._deprecated('create_annotated_heatmap') from plotly.figure_factory import create_annotated_heatmap return create_annotated_heatmap(*args, **kwargs)