def build_2d_density(self, **data): df = data['df'] n_records = self.set_size(**data) columns = data['columns'] return ff.create_2d_density(df[:n_records][columns[0]], df[:n_records][columns[1]])
def drawHistogram(data, accuracyName, variableName): x = [d[variableName] for d in data] y = [d[accuracyName] for d in data] colorscale = ['rgb(255,0,0)', (1,1,1)] f = ff.create_2d_density( x, y, colorscale=colorscale, hist_color='rgb(255, 237, 222)', point_size=3, title='', height=1080, width=1920) return f
def CC_viz(df, charter='Plotly', output_chart=False, output_dir=None, resolution=150, display=False): ''' Takes two continuous feature names and generates a 2D Kernel Density Plot ''' U = list(df.columns)[0] V = list(df.columns)[1] if charter == 'Plotly': fig = ff.create_2d_density(df[U], df[V], colorscale=px.colors.sequential.Blues_r, hist_color=(135 / 255, 206 / 255, 250 / 255), title='') fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False, xaxis_title=U.replace('_', ' ').title(), yaxis_title=V.replace('_', ' ').title(), plot_bgcolor="rgba(0, 0, 0, 0)", paper_bgcolor="rgba(0, 0, 0, 0)", showlegend=False) if display: fig.show() if output_chart: fig.update_xaxes(tickcolor='white', tickfont=dict(color='white')) fig.update_yaxes(tickcolor='white', tickfont=dict(color='white')) fig.update_layout(font=dict(color="white")) fig.write_image(str(output_dir / 'charts' / (U + '_' + V + '.png')), scale=resolution // 72) else: sns.kdeplot(df[U], df[V], color='blue', shade=True, alpha=0.3, shade_lowest=False) if len(df[U]) < 500: sns.scatterplot( x=df[U], y=df[V], color='blue', alpha=0.5, linewidth=0 ) # Only show a scatter plot if there are fewer than 500 data points plt.xlabel(U.replace('_', ' ').title()) plt.ylabel(V.replace('_', ' ').title()) if display: plt.show() if output_chart: plt.savefig(output_dir / 'charts' / (U + '_' + V + '.png'), dpi=resolution) plt.close('all')
import pandas as pd iris = load_iris() columns = ["label"] + iris.feature_names label = iris.target.reshape([150, 1]) labeled = np.hstack([label, iris.data]) # make dataframe df = pd.DataFrame(labeled, columns=columns) # setosaのsepal-lengthとsepal-widthを使います. setosa = df[df["label"] == 0] x = setosa['sepal length (cm)'] y = setosa['sepal width (cm)'] # define colorscale colorscale = [ '#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2), (0.98, 0.98, 0.98) ] fig = ff.create_2d_density( x, y, colorscale=colorscale, hist_color='rgb(0, 128, 222)', point_size=3, ) offline.plot(fig, filename="2d-density", image="png")
def create_2D_density(*args, **kwargs): FigureFactory._deprecated('create_2D_density', 'create_2d_density') from plotly.figure_factory import create_2d_density return create_2d_density(*args, **kwargs)
buildTagData(tags, plots) """ ------------------------------------------------------------------------------- --------------------------Creating the plotly figures-------------------------- ------------------------------------------------------------------------------- """ scatterPointFigure = px.scatter(combinedFrame, x="x", y="y", color="tag", title="Scatter attempt") heatmapFigure = create_2d_density(combinedFrame.x, combinedFrame.y, colorscale=colorscale, hist_color='rgb(255, 237, 222)', point_size=1, title='2D Density Plot', height=1200, width=1200) trackingFigureAnimated = go.Figure( data=getAllInitialData(MinuteFrameList, len(MinuteFrameList)), layout=go.Layout( xaxis=dict(range=[-xMinMax - 10, xMinMax + 10], autorange=False), yaxis=dict(range=[-yMinMax - 10, yMinMax + 10], autorange=False), title="All Tag Tracker", updatemenus=[ dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])]) ], height=800),
############################################################################## # Scatter Histogram # --------------------------------------------------------------------------- # Source: # https://plot.ly/python/density-plots/ # https://plot.ly/python/2d-density-plots/ ############################################################################## import numpy as np import plotly import plotly.figure_factory as ff t = np.linspace(-1, 1.2, 2000) x = (t**3) + (0.3 * np.random.randn(2000)) y = (t**6) + (0.3 * np.random.randn(2000)) colorscale = ['#426d9f', (1, 1, 1)] fig = ff.create_2d_density(x, y, colorscale=colorscale, ncontours=20, hist_color='#c4e0f9', point_size=1.5, point_color=(0.0, 0.0, 0.0)) plotly.offline.iplot(fig, filename='histogram_subplots') plotly.offline.plot(fig, filename='scatterHistogram.html')
def scatter(x, y, legacy, names, path, plots, color, colormap, settings, stat=None, log=False, minvalx=0, minvaly=0, title=None, xmax=None, ymax=None): """-> create marginalised scatterplots and KDE plot with marginalized histograms -> update from scatter_legacy function to utilise plotly package - scatterplot with histogram on both axes - kernel density plot with histograms on both axes - hexbin not implemented yet - pauvre plot temporarily not available """ logging.info( f"NanoPlot: Creating {names[0]} vs {names[1]} plots using {x.size} reads." ) if not contains_variance([x, y], names): return [] plots_made = [] idx = np.random.choice(x.index, min(10000, len(x)), replace=False) maxvalx = xmax or np.amax(x[idx]) maxvaly = ymax or np.amax(y[idx]) if plots["dot"]: if log: dot_plot = Plot(path=path + "_loglength_dot.html", title=f"{names[0]} vs {names[1]} plot using dots " "after log transformation of read lengths") else: dot_plot = Plot(path=path + "_dot.html", title=f"{names[0]} vs {names[1]} plot using dots") fig = px.scatter(x=x[idx], y=y[idx], marginal_x="histogram", marginal_y="histogram", range_x=[minvalx, maxvalx], range_y=[minvaly, maxvaly]) fig.update_traces(marker=dict(color=color)) fig.update_yaxes(rangemode="tozero") fig.update_xaxes(rangemode="tozero") fig.update_layout(xaxis_title=names[0], yaxis_title=names[1], title=title or dot_plot.title, title_x=0.5) if log: ticks = [ 10**i for i in range(10) if not 10**i > 10 * (10**maxvalx) ] fig.update_layout(xaxis=dict(tickmode='array', tickvals=np.log10(ticks), ticktext=ticks, tickangle=45)) dot_plot.fig = fig dot_plot.html = dot_plot.fig.to_html(full_html=False, include_plotlyjs='cdn') dot_plot.save(settings) plots_made.append(dot_plot) if plots["kde"]: kde_plot = Plot(path=path + "_loglength_kde.html" if log else path + "_kde.html", title=f"{names[0]} vs {names[1]} kde plot") col = hex_to_rgb_scale_0_1(color) fig = ff.create_2d_density(x[idx], y[idx], point_size=3, hist_color=col, point_color=col, colorscale=colormap) fig.update_layout(xaxis_title=names[0], yaxis_title=names[1], title=title or kde_plot.title, title_x=0.5, xaxis=dict(tickangle=45)) if log: ticks = [ 10**i for i in range(10) if not 10**i > 10 * (10**maxvalx) ] fig.update_layout(xaxis=dict(tickmode='array', tickvals=np.log10(ticks), ticktext=ticks, tickangle=45)) kde_plot.fig = fig kde_plot.html = kde_plot.fig.to_html(full_html=False, include_plotlyjs='cdn') kde_plot.save(settings) plots_made.append(kde_plot) if 1 in legacy.values(): settings, args = utils.get_args() plots_made += scatter_legacy(x=x[idx], y=y[idx], names=names, path=path, plots=legacy, color=color, settings=settings, stat=stat, log=log, minvalx=minvalx, minvaly=minvaly, title=title) return plots_made
########### This is about using figure_factory module instead of graph_objs module of plotly to plot a 2D density plot ################ import plotly.offline as offline import plotly.figure_factory as ff pubg = pd.read_csv('PUBG.csv') df_pubg = pubg.apply(pd.to_numeric, errors="ignore") df_bar_pubg = df_pubg.head(10) x = df_bar_pubg['solo_Wins'] y = df_bar_pubg['solo_TimeSurvived'] #z = df_bar_pubg['squad_Heals'] colorscale = ['#C09055', '#1B5709', '#FF8237', '#FF65A4', '#C8B4FF'] fig = ff.create_2d_density(x, y, colorscale=colorscale, hist_color='rgb(255,237,222)', point_size='3') offline.plot(fig, filename='histogram_subplots')