def update_figure(input1, input2, input3, input4, input5): Final = pd.DataFrame() df11 = pd.DataFrame() df12 = pd.DataFrame() df13 = pd.DataFrame() df14 = pd.DataFrame() df1 = df.query('pitcher_id == @input1') df2 = df1.query('pitch_type == @input2') df11 = df11.append(df2) #for l in input5: df3 = df11.query('stand == @input5') df12 = df12.append(df3) #for j in input4: df4 = df12.query('b_count == @input3') df13 = df13.append(df4) #for k in input3: df5 = df13.query('s_count == @input4') Final = Final.append(df5) print(Final.shape) try: trace_2 = go.Histogram2d(x=Final.px, y=Final.pz, colorscale=[[0, "rgb(255,255,255)"], [0.25, "rgb(214,181,226)"], [0.45, "rgb(181,146,196)"], [0.65, "rgb(138,111,166)"], [0.85, "rgb(111,76,179)"], [1, "rgb(82,40,136)"]], reversescale=False) fig = go.Figure(data=[trace_2], layout=layouts) fig.layout.update(shapes=[ # unfilled Rectangle go.layout.Shape(type="rect", x0=-.7083, y0=1.56, x1=.7083, y1=3.435, line=dict(color="Black", )) ]) return fig except AttributeError: trace_2 = go.Histogram2d(x=df1.px, y=df1.pz, colorscale='Blues', reversescale=True) fig = go.Figure(data=[trace_2], layout=layouts) fig.layout.update(shapes=[ # unfilled Rectangle go.layout.Shape(type="rect", x0=-.7083, y0=1.56, x1=.7083, y1=3.435, line=dict(color="Black", )) ]) return fig
def create_trace(settings): return [ graph_objs.Histogram2d( x=settings.x, y=settings.y, colorscale=settings.properties['color_scale']) ]
def plot2d(): t = np.linspace(-1,1,2000) x = (t**2)+(0.5*np.random.randn(2000)) y = (t**2)+(0.5*np.random.randn(2000)) trace1 = go.Scatter( x=x, y=y, mode='markers', name='points', marker=dict(color='rgb(0,0,0)', size=2, opacity=0.4) ) trace2 = go.Histogram2d( x=x, y=y, name='density', nbinsx=100, nbinsy=100, colorscale='Jet', reversescale=False, showscale=True ) trace3 = go.Histogram( x=x, name='x density', marker=dict(color='blue'), yaxis='y2' ) trace4 = go.Histogram( y=y, name='y density', marker=dict(color='blue'), xaxis='x2' ) data = [trace1, trace2, trace3, trace4] layout = go.Layout( showlegend=False, autosize=False, width=800, height=700, xaxis=dict( domain=[0, 0.85], showgrid=False, zeroline=False ), yaxis=dict( domain=[0, 0.85], showgrid=False, zeroline=False ), margin=dict( t=50 ), hovermode='closest', bargap=0, xaxis2=dict( domain=[0.85, 1], showgrid=False, zeroline=False ), yaxis2=dict( domain=[0.85, 1], showgrid=False, zeroline=False ) ) fig = go.Figure(data=data, layout=layout) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div
def update_figure(input1, input2, input3, input4, input5): Final = df.query( 'pitcher_id == @input1 and pitch_type == @input2 and stand == @input5 and b_count == @input3 and s_count == @input4' ) trace_2 = go.Histogram2d(x=Final.px, y=Final.pz, colorscale=teamColor, reversescale=False) fig = go.Figure(data=[trace_2], layout=layouts) fig.layout.update( title=go.layout.Title(text="View From Catcher's Viewpoint"), xaxis=go.layout.XAxis(title=go.layout.xaxis.Title( text="Distance From Center of Home Plate (in feet)")), yaxis=go.layout.YAxis(title=go.layout.yaxis.Title( text="Distance From Ground (in feet, negative means it bounced)")), shapes=[ # unfilled Rectangle go.layout.Shape(type="rect", x0=-.7083, y0=1.56, x1=.7083, y1=3.435, line=dict(color="Black", )) ]) gc.collect() return fig
def plot_heatmap(self): """ :return: heatmap of projection onto normal SOM """ if self.project is None: som_dist_calc = np.asarray([ self.dist_uarray(i) for i in tqdm(range(self.som_te.window_data.shape[0]), desc="mapping online set") ]) self.project = som_dist_calc[:, 1] xdim = self.som_grid.net_dim[0] x = self.project % xdim y = self.project // xdim if self.som_grid.topo == "rectangular": fig = go.Figure(go.Histogram2d(x=x, y=y, colorscale="Viridis")) fig.show() elif self.som_grid.topo == "hexagonal": x = x + .5 * (y % 2) y = np.sqrt(3) / 2 * y # plt_hex = plt.hexbin(x, y) # plt.close() # fig = tls.mpl_to_plotly(plt_hex) plt.hexbin(x, y) plt.show()
def create_2d_histogram(df, xaxis, yaxis, title): """ This method will create a 2d histogram (heatmap) Args: df (pandas.DataFrame): data that will be displayed xaxis (str): x axis header yaxis (str): y axis header title (str): plot title Returns: figure dict object formatted for plotly """ # Create data data = [go.Histogram2d(x=df[xaxis], y=df[yaxis])] # Create layout layout = { 'title': title, 'xaxis': { 'title': xaxis }, 'yaxis': { 'title': yaxis } } fig = {'data': data, 'layout': layout} return fig
def histogram_2d(x, y, df, title, xlabel, ylabel, xticks, yticks, ytitle=0.9, width=1000, height=550, colorscale="RdBu"): """ Parameters: ----------- x : the column to be plotted on the x-axis : str : : y : the column to be plotted on the y-axis : str : : df : dataframe source of data : dataframe : : title : title for the graph : str : : xlabel : label for the x-axis : str : : ylabel : label for the y-axis : str : : xticks : tick range for the x-axis : np.arange : : yticks : tick range for the y-axis : np.arange : : ytitle : how high above the plot to place the title : float : : width : width of the plot : int : : height : height of the plot : int : : colorscale : color scale to map overlapping of data points : str : : Description: ------------ Plots two continuous columns against each other and shows overlapping points with a color scale and gives the user greater customization over the plot. Returns: -------- Creates a single two-dimensional histogram with the input dimensions. """ fig = go.Figure( go.Histogram2d(x=df[x], y=df[y], colorscale=colorscale, colorbar=dict(outlinewidth=1))) fig.update_layout(title=dict(text=title, y=ytitle, x=0.5, xanchor="center", yanchor="top"), xaxis_title=xlabel, yaxis_title=ylabel, width=width, height=height) fig.update_xaxes(tickvals=xticks, title_font=dict(size=18), tickfont=dict(size=14)) fig.update_yaxes(tickvals=yticks, title_font=dict(size=18), tickfont=dict(size=14)) fig.show()
def create_plots(df): df[['Day', 'Month', 'Year']] = df['Date'].str.split('/', expand=True) result = db.engine.execute( "select split_part(date_recorded, '/', 1) as day, split_part(date_recorded, '/', 2) as month," "split_part(date_recorded, '/', 3) as year, avg(temperature) as t, sum(rented_bikes) as " "count from bike_data group by 1,2,3 order by 3, 2, 1;") date = [] count = [] temp = [] for x in result: date.append( str(x['day']) + "/" + str(x['month']) + "/" + str(x['year'])) count.append(x['count']) temp.append(ceil(x['t'])) scatter_df = pd.DataFrame() scatter_df['Date'] = date scatter_df['Bike Count'] = count scatter_df['temp'] = temp plots = [] data = [ go.Scatter(x=scatter_df['Date'], y=scatter_df['Bike Count'], mode="markers", marker=dict(color='#838df9')) ] plots.append(json.dumps(data, cls=PlotlyJSONEncoder)) data_2 = [ go.Bar(y=scatter_df['temp'], x=scatter_df['Bike Count'], orientation='h', marker=dict(color='#ec7a69')) ] plots.append(json.dumps(data_2, cls=PlotlyJSONEncoder)) data_3 = [ go.Histogram(y=df['Rented Bike Count'], marker=dict(color='#636efa')) ] plots.append(json.dumps(data_3, cls=PlotlyJSONEncoder)) data_4 = [ go.Histogram2d(x=df['Humidity(%)'], y=df['Temperature(C)'], z=df['Rented Bike Count'], histfunc="avg") ] plots.append(json.dumps(data_4, cls=PlotlyJSONEncoder)) return plots
def histogram2dGraph(data, labels): traces = [ go.Histogram2d(x=data[labels["x"].get()], y=data[labels["y"].get()], colorscale='Cividis', colorbar=dict(title="Count")) ] fig = dict(data=traces, layout=dict(title="Histogram of " + labels["y"].get() + " vs. " + labels["x"].get(), yaxis=dict(title=labels["y"].get()), xaxis=dict(title=labels["x"].get()))) pl.plot(fig) return
def return_core_histogram(xdata): global glob_det_x, glob_det_y,glob_id x=xdata['core_x'] xrange=[-240,240] xbinsize=10 y=xdata['core_y'] yrange=[-240,240] ybinsize=10 traces=[] traces.append( go.Histogram2d(x=x, y=y, autobinx=False, xbins=dict(start=xrange[0], end=xrange[1], size=xbinsize), autobiny=False, ybins=dict(start=yrange[0], end=yrange[1], size=ybinsize), colorscale=mycmap, colorbar = {'thickness':15,'title':'counts'}, zmin=0, )) traces.append( go.Scatter(x=glob_det_x, y=glob_det_y,text=glob_id, mode='markers',name='Detectors', marker={'color':'rgba(0, 0, 0, 0.0)',#transparent circle. 'line':{'width':1,'color':'black'},'size':8, }) ) return { 'data': traces, 'layout': { 'hovermode': 'closest', 'title': 'Approx. Core Histogram', 'titlefont':{'size':26}, 'xaxis':{'title':'X (m)', 'titlefont':{'size':24}, 'zeroline':False, 'dtick':80, 'showgrid':False, 'tickfont':{'size':12}}, 'yaxis':{'title':'Y (m)', 'titlefont':{'size':24}, 'zeroline':False, 'showgrid':False, 'dtick':80, 'tickfont':{'size':12}}, } }
def cala_gestosc(n, moves): data = [] for i in range(0, n): data.append(gestosc(moves)) rozklad = np.zeros((20, 20)) for i in range(0, n): X = int(np.floor(data[i][moves - 1][0] / 10)) Y = int(np.floor(data[i][moves - 1][1] / 10)) if -10 < X < 10 and -10 < Y < 10: rozklad[X + 10][Y + 10] += 1 layout = go.Layout(showlegend=False) data = go.Histogram2d() fig = go.Figure(data=data, layout=layout) py.plot(fig, filename='surface')
def build_week_heat_map(self, title): ''' This function is in charge of building a single 2D Histogram trace specifically for a DOW plot, i.e. week day on x-axis, and hour of the day (HOD) on y-axis. ''' hist = go.Histogram2d(y=self.df['Play_HOD'], x=self.df['Play_DOW'], ybins=dict(start=0.5, end=23.5, size=1), z=self.df['Play_duration_in_minutes'], histfunc="sum", hovertemplate=title + " - %{x}s, %{y}h<b><br>" + "Time listening: %{z:,.0f} minutes<br>" + "<extra></extra>", coloraxis="coloraxis") self.data = hist
def build_day_heat_map(self, title): ''' This function is in charge of building a single 2D Histogram trace specifically for a DOM plot, i.e. month on x-axis, and day of the month (DOM) on y-axis. ''' hist = go.Histogram2d( y=self.df['Play_DOM'], x=self.df['Play_Month'], autobiny=False, ybins=dict(start=1.5, end=31.5, size=1), autobinx=False, xbins=dict(start=0.5, end=12.5, size=1), z=self.df['Play_duration_in_minutes'], histfunc="sum", hovertemplate="<b>%{y} %{x}</b><b> " + title + "<b><br>" + "Time listening: %{z:,.0f} minutes<br>" + "<extra></extra>", coloraxis="coloraxis") self.data = hist
def hist2d(x, y, label=None, opacity=None): """2D Histogram. Parameters ---------- x : array-like, optional y : array-like, optional label : TODO, optional opacity : float, optional Returns ------- Chart """ x = np.atleast_1d(x) y = np.atleast_1d(y) data = [go.Histogram2d(x=x, y=y, opacity=opacity, name=label)] return Chart(data=data)
def plot_hist(dataFrame, xlabel, ylabel, title): """ This function plot histgrams to plotly :param dataFrame the input data :param xlabel, ylabel the labels of the plot :param title the title of the histgram """ # Create traces hist_trace = go.Histogram2d(x=dataFrame[xlabel], y=dataFrame[ylabel]) # Assign it to an iterable object named myData hist_Data = [hist_trace] # Add axes and title to histogram hist_Layout = go.Layout(title=title, xaxis=dict(title=xlabel), yaxis=dict(title=ylabel)) # Setup figure hist_Figure = go.Figure(data=hist_Data, layout=hist_Layout) # Display the scatterplot hist_Figure.show() py.plot(hist_Figure)
def plot_heatmap(self, data): """ :return: Heatmap for SOM """ if self.project is None: normal_distance = np.asarray([ self.dist_weight(data, i) for i in tqdm(range(data.shape[0]), desc="mapping") ]) self.dist_normal = normal_distance[:, 0] self.project = normal_distance[:, 1] x = self.project % self.net_dim[0] y = self.project // self.net_dim[0] if self.topo == "rectangular": fig = go.Figure(go.Histogram2d(x=x, y=y, colorscale="Viridis")) fig.show() elif self.topo == "hexagonal": x = x + .5 * (y % 2) y = np.sqrt(3) / 2 * y # plt_hex = plt.hexbin(x, y) # plt.close() # fig = tls.mpl_to_plotly(plt_hex) plt.hexbin(x, y) plt.show()
def update_figure(input1, input2, input3, input4, input5): Final = pd.DataFrame() df11 = pd.DataFrame() df12 = pd.DataFrame() df13 = pd.DataFrame() df14 = pd.DataFrame() df1 = df.query('pitcher_id == @input1') df2 = df1.query('pitch_type == @input2') df11 = df11.append(df2) #for l in input5: df3 = df11.query('stand == @input5') df12 = df12.append(df3) #for j in input4: df4 = df12.query('b_count == @input3') df13 = df13.append(df4) #for k in input3: df5 = df13.query('s_count == @input4') Final = Final.append(df5) print(Final.shape) try: trace_2 = go.Histogram2d(x=Final.px, y=Final.pz, colorscale=teamColor, reversescale=False) fig = go.Figure(data=[trace_2], layout=layouts) fig.layout.update( title=go.layout.Title(text="View From Catcher's Viewpoint"), xaxis=go.layout.XAxis(title=go.layout.xaxis.Title( text="Distance From Center of Home Plate (in feet)")), yaxis=go.layout.YAxis(title=go.layout.yaxis.Title( text="Distance From Ground (in feet, negative means it bounced)" )), shapes=[ # unfilled Rectangle go.layout.Shape(type="rect", x0=-.7083, y0=1.56, x1=.7083, y1=3.435, line=dict(color="Black", )) ]) return fig except AttributeError: trace_2 = go.Histogram2d(x=df1.px, y=df1.pz, colorscale='Blues', reversescale=True) fig = go.Figure(data=[trace_2], layout=layouts) fig.layout.update(shapes=[ # unfilled Rectangle go.layout.Shape(type="rect", x0=-.7083, y0=1.56, x1=.7083, y1=3.435, line=dict(color="Black", )) ]) return fig1 #increase num
""" import plotly import plotly.graph_objs as go infile = "JSON/sentiment_stars_tenpercent_sample.txt" count = 0 sentiment, star = [], [] print "Initialized; processing data file..." with open(infile) as f: for line in f: sentiment_val = float(line[0:-3]) if sentiment_val < 0.8: sentiment.append(sentiment_val) star.append(int(line[-2:-1])) count += 1 print "Processing finished; making histogram..." trace0 = go.Histogram2d(x=sentiment, y=star) data = [trace0] layout = go.Layout(title='Star Rating vs Sentiment', xaxis=dict(title='Sentiment', titlefont=dict(size=18)), yaxis=dict(title='Star Rating', titlefont=dict(size=18))) fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='sentiment_stars_2d_histogram_below_point8.html') print "Done!"
'value': '2.0' } ] battercol = [ { 'label': 'Right', 'value': 'R' }, #increase num { 'label': 'Left', 'value': 'L' } ] trace_1 = go.Histogram2d() layouts = go.Layout(height=600, width=600) figcol = go.Figure(data=[trace_1], layout=layouts) #increase num value = opts[0]['value'] def counts(s, b, hand, pitcher): pitches = df.query('pitcher_id == @pitcher').pitch_type.unique() j = 0 i = 0 bc = ['0', '1', '2', '3'] sc = ['0', '1', '2'] final = pd.DataFrame(data=pitches, columns=['Pitch Type']) for st in s:
def shot_freq_heatmap(name): if name in df.name.unique(): df_ = df[df.name == name] z_max = 40 z_min = 0 else: df_ = df[df.team_name == name] z_max = 250 z_min = 5 x_make = df_[df_.shot_made_flag == 1]['x'] y_make = df_[df_.shot_made_flag == 1]['y'] x_miss = df_[df_.shot_made_flag == 0]['x'] y_miss = df_[df_.shot_made_flag == 0]['y'] x = np.concatenate([x_make, x_miss]) y = np.concatenate([y_make, y_miss]) makes = go.Scatter(x=x_make, y=y_make, mode='markers', name='Make', showlegend=True, marker=dict( symbol='circle', opacity=0.7, color='green', size=4, line=dict(width=1), )) misses = go.Scatter(x=x_miss, y=y_miss, mode='markers', name='Miss', showlegend=True, marker=dict( symbol='x', opacity=0.7, color='yellow', size=4, line=dict(width=1), )) trace3 = go.Histogram2d( x=x, y=y, zmax=z_max, zmin=z_min, # nbinsx=20, # nbinsy=20, zsmooth='best', autobinx=True, autobiny=True, reversescale=False, opacity=.75, #zauto=True, #autocolorscale=True, ) layout = go.Layout( xaxis=dict(ticks='', showgrid=False, zeroline=False, nticks=20, range=[-250, 250]), yaxis=dict(ticks='', showgrid=False, zeroline=False, nticks=20, range=[-47.5, 450]), autosize=False, height=600, width=750, hovermode='closest', shapes=court_shapes, title=name + ' - Shot Frequency Heatmap', showlegend=True, legend=dict(x=1.2, y=1), ) data = [trace3] #, makes, misses] fig = go.Figure(data=data, layout=layout) plotly.offline.iplot(fig)
def Update_ESOI_layer_struc(select_stage): id = int(select_stage) edgex = [] edgey = [] adjacency = np.zeros(len(total_2D_data[id])) if id < len(GPARAMS.Esoinn_setting.Model.learn_history_edge): nodelist=go.Scatter(x=total_2D_data[id][:,0],y=total_2D_data[id][:,1],text="Stage%d"%id,name="Stage%d"%id,\ mode="markers",hoverinfo='text', marker=dict(showscale=True,colorscale='YlGnBu',reversescale=True,color=[],size=10,\ colorbar=dict(thickness=15,title='Node Connections',xanchor='right',titleside='right'),\ line_width=2)) for j in GPARAMS.Esoinn_setting.Model.learn_history_edge[id]: total_2D_data[id] = np.array(total_2D_data[id]) edgex += list(total_2D_data[id][j, 0]) + [None] edgey += list(total_2D_data[id][j, 1]) + [None] adjacency[j[0]] += 1 else: nodelist=go.Scatter(x=total_2D_data[id][:,0],y=total_2D_data[id][:,1],text="Stage%d"%id,name="Stage%d"%id,\ mode="markers",hoverinfo='text', marker=dict(size=10,\ line_width=2)) for j in list(GPARAMS.Esoinn_setting.Model.adjacent_mat.keys()): edgex += list(total_2D_data[id][j, 0]) + [None] edgey += list(total_2D_data[id][j, 1]) + [None] adjacency[j[0]] += 1 edgelist = go.Scatter(x=edgex, y=edgey, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines') node_text = [ '#with %d connections' % adjacency[j] for j in range(len(adjacency)) ] if id < len(GPARAMS.Esoinn_setting.Model.learn_history_edge): nodelist.marker.color = adjacency else: sizelist = np.array(GPARAMS.Esoinn_setting.Model.density) maxsize = np.max(sizelist) minsize = np.min(sizelist) sizelist = (sizelist - minsize) / (maxsize - minsize) * 90 + 10 nodelist.marker.size = sizelist node_text = [ 'Density %.2f' % GPARAMS.Esoinn_setting.Model.density[j] for j in range(len(sizelist)) ] nodelist.text = node_text x0 = np.array(total_2D_data[id][:, 0]) y0 = np.array(total_2D_data[id][:, 1]) histogram2d=go.Histogram2d(x=x0,\ y=y0,\ histnorm='probability', colorscale='YlGnBu', nbinsx=50, nbinsy=50) ESOILayout = go.Layout(showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False), autosize=False, height=600, clickmode='event+select') ESOILayer = { "data": [histogram2d, edgelist, nodelist], "layout": ESOILayout } return ESOILayer
bestN_loc_err = results[results[:, loc_err_i].argsort()][0:bestN] bestN_ori_err = results[results[:, ori_err_i].argsort()][0:bestN] data = bestN_loc_err ##################################### # data preparation ##################################### plots = np.empty((num_params, num_params), dtype=object) for i in range(num_params): for j in range(num_params): plots[i, j] = go.Histogram2d( x=np.sort(data[:, p_arr_i[i]]), y=np.sort(data[:, p_arr_i[j]]), ) # plots[i,j] = go.Scatter( # x = data[:,p_arr_i[i]], # y = data[:,p_arr_i[j]], # mode = 'markers', # marker = dict(color = data[:,loc_err_i]) # ) fig = tools.make_subplots(rows=num_params, cols=num_params) for i in range(num_params): for j in range(num_params): fig.append_trace(plots[i, j], i + 1, j + 1)
def histogram2d(self, *args, **kwargs): """A proxy for plotly.graph_objs.Histogram2d""" self._data.append(go.Histogram2d(*args, **kwargs))
# -*- coding: utf-8 -*- """ Created on Sun Sep 17 07:25:04 2017 @author: Terada """ import plotly.offline as offline import plotly.graph_objs as go offline.init_notebook_mode() import numpy as np x = np.random.randn(500) y = np.random.randn(500) + 1 trace = go.Histogram2d(x=x, y=y, name="data1", opacity=0.75, colorscale="YIGnBu") layout = go.Layout( title="2d histograms", xaxis=dict(title="data1"), yaxis=dict(title="data2"), ) fig = dict(data=[trace], layout=layout) offline.plot(fig, filename='2d_histogram', image="png")
from plotly import graph_objs as plgo import dash import dash_core_components as dcc import dash_html_components as html from dash import dependencies as ddp data = pd.read_csv('pokemons.csv') data.type2 = data.type2.fillna(data.type1) ### Figure 1 ### fig1 = plgo.Figure() trace = plgo.Histogram2d() trace.x = data.type2 trace.y = data.type1 trace.colorscale = [ (0, '#B0FF60'), # green (1 / 16, '#FFFF60'), # yellow (1 / 4, '#FFB060'), # orange (1, '#FF6060'), # red ] fig1.add_trace(trace) fig1.layout.title = 'Pokemon Heatmap' fig1.layout.xaxis.title = 'Main type' fig1.layout.yaxis.title = 'Secondary type' # fig1.layout.height = 600
def spikeScatter(dfUnits, histType='sc', groupBy='Unit', xBin=40, yBin=36, xDim=1024, yDim=768, tsInt=.03125): """ Creates a plot.ly graph from the provided pandas Dataframe, showing firing location for each spike as a scatter point. Optionally creates a 2D histogram with spike scatter plot as an overlay. Note that histogram is calculated for all scatter points in the dataframe and does not distinguish by group Inputs: dfUnits: A pandas dataframe with the following columns: Timestamp X Y Unit DateTime histType: String parameter for controlling histogram type, with following options: 'sc' for spike count histogram, 'fr' for avg. firing rate histogram, '' or None for nothing groupBy: String parameter for controlling how scatter points are grouped (color code): 'Unit' for unit name, 'DateTime' for recording datetime. For now whichever is used for color coding, the other will be in the hovertext for each point tsInt: Float # representing the sampling interval used by cineplex tracker, translates to """ # Get unit names and segment DateTimes, will be used for grouping segDates = pd.unique(dfUnits['DateTime']) if groupBy == 'Unit': nameList = pd.unique(dfUnits['Unit']) # hoverList = pd.unique(dfUnits['DateTime']) elif groupBy == 'DateTime': nameList = pd.unique(dfUnits['DateTime']) # hoverList = pd.unique(dfUnits['Unit']) data = [] # Loop over every group being plotted for i in range(len(nameList)): # EXPERIMENTAL Using ScatterGL to leverage WebGL rendering, should be useful for when dealing # with large numbers of spikes trace = go.Scattergl( x=dfUnits[dfUnits[groupBy] == nameList[i]]['X'], y=dfUnits[dfUnits[groupBy] == nameList[i]]['Y'], name=nameList[i], mode='markers', ) data.append(trace) histTrace = go.Histogram2d( x=dfUnits['X'], autobinx=False, xbins=dict(start=0, end=xDim, size=xDim / xBin), y=dfUnits['Y'], autobiny=False, ybins=dict(start=0, end=yDim, size=yDim / yBin), zsmooth='', histnorm='', histfunc='', colorbar=dict(x=1.15), colorscale='Viridis', ) data.append(histTrace) fig = go.Figure(data=data) offline.plot(fig)
'value': '2.0' } ] balaa = [ { 'label': 'Right', 'value': 'R' }, #increase num { 'label': 'Left', 'value': 'L' } ] trace_1 = go.Histogram2d(x=df.px, y=df.pz, colorscale=teamColor) layouts = go.Layout(height=600, width=600) figlaa = go.Figure(data=[trace_1], layout=layouts) #increase num value = opts[0]['value'] def counts(s, b, hand, pitcher): pitches = df.query('pitcher_id == @pitcher').pitch_type.unique() j = 0 i = 0 bc = ['0', '1', '2', '3'] sc = ['0', '1', '2'] final = pd.DataFrame(data=pitches, columns=['Pitch Type']) for st in s:
def update_graph(chart): trace1 = [] for age in ['0-17', '18-25', '26-35', '36-45', '46-50', '51-55', '55+']: trace1.append( go.Box(y=df[df["Age Group"] == age]['Purchase'], name=age)) layout1 = go.Layout(title="Purchase vs Age group", xaxis={"title": "Age Group"}, yaxis={"title": "Sales ($)"}, colorway=[ '#b2182b', '#ef8a62', '#fddbc7', '#E7E7E7', '#d1e5f0', '#67a9cf', '#2166ac' ]) df_bar = df.groupby(["Occupation"])['Purchase'].sum().reset_index() trace2 = [ go.Bar(x=df_bar["Occupation"], y=df_bar["Purchase"], marker={ 'color': '#ef8a62', 'line': { 'color': "#b2182b", 'width': 0.5 } }, opacity=0.6, error_y={ 'type': 'percent', 'value': 10 }) ] layout2 = go.Layout(title="Purchase vs Occupation Types", xaxis={"title": "Occupation Category (20 Types)"}, yaxis={"title": "Sales ($)"}) trace3 = [] for product in ['Product 1', 'Product 2', 'Product 3']: trace3.append( go.Histogram(x=df[product], name=product, xbins={"size": 3}, opacity=0.8)) layout3 = go.Layout(title="Product Category Distribution", xaxis={"title": "Products"}, yaxis={"title": "Frequency"}, barmode='overlay', colorway=['#e9a3c9', '#ffffbf', '#a1d76a']) trace4 = [ go.Histogram2d(x=df["Age Group"].sort_values(), y=df['Purchase'], histnorm='probability', autobinx=False, xbins={"size": 1}, autobiny=False, ybins={"size": 1000}, colorscale=[[0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'], [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'], [1, 'rgb(217,30,30)']]) ] layout4 = go.Layout(title="Sales vs Age Group distribution", xaxis={"title": "Age Group"}, yaxis={"title": "Sales ($)"}) x1 = df[df["City"] == "A"]["Purchase"] x2 = df[df["City"] == "B"]["Purchase"] x3 = df[df["City"] == "C"]["Purchase"] hist_data = [x1, x2, x3] group_labels = ["City A", "City B", "City C"] figure5 = ff.create_distplot(hist_data, group_labels, bin_size=1000, colors=['#a6cee3', '#1f78b4', '#b2df8a']) figure5['layout'].update(title='Sales Distribution Over Cities', yaxis={"title": " Probability Density of Sales"}) trace6 = [{ "type": 'violin', "x": df[df['Gender'] == 'M']["Resident of the current city"], "y": df[df['Gender'] == 'M']["Purchase"], "legendgroup": 'M', "scalegroup": 'M', "name": 'Male', "box": { "visible": True }, "meanline": { "visible": True }, "line": { "color": '#C1EC00' } }, { "type": 'violin', "x": df[df['Gender'] == 'F']["Resident of the current city"], "y": df[df['Gender'] == 'F']["Purchase"], "legendgroup": 'F', "scalegroup": 'F', "name": 'Female', "box": { "visible": True }, "meanline": { "visible": True }, "line": { "color": '#EC7899' } }] layout6 = go.Layout(title="Sales Distribution Over Duration of Stay", xaxis={"title": " Duration of Stay (years)"}, yaxis={"title": "Sales ($)"}, violinmode="group") if chart == "Box Plot": return {"data": trace1, "layout": layout1} elif chart == "Error Bar": return {"data": trace2, "layout": layout2} elif chart == "Histogram": return {"data": trace3, "layout": layout3} elif chart == "2D Histogram": return {"data": trace4, "layout": layout4} elif chart == "Distplot": return figure5 else: return {"data": trace6, "layout": layout6}
def buildTrace(self): ''' build the final trace calling the go.xxx plotly method this method here is the one performing the real job From the initial object created (e.g. p = Plot(plot_type, plot_properties, layout_properties)) this methods checks the plot_type and elaborates the plot_properties dictionary passed Console usage: # create the initial object p = Plot(plot_type, plot_properties, layout_properties) # call the method p.buildTrace() Returns the final Plot Trace (final Plot object, AKA go.xxx plot type) ''' if self.plot_type == 'scatter': self.trace = [go.Scatter( x=self.plot_properties['x'], y=self.plot_properties['y'], mode=self.plot_properties['marker'], name=self.plot_properties['name'], ids=self.plot_properties['featureIds'], customdata=self.plot_properties['custom'], text=self.plot_properties['additional_hover_text'], hoverinfo=self.plot_properties['hover_text'], marker=dict( color=self.plot_properties['in_color'], colorscale=self.plot_properties['colorscale_in'], showscale=self.plot_properties['show_colorscale_legend'], reversescale=self.plot_properties['invert_color_scale'], colorbar=dict( len=0.8 ), size=self.plot_properties['marker_size'], symbol=self.plot_properties['marker_symbol'], line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ) ), line=dict( width=self.plot_properties['marker_width'], dash=self.plot_properties['line_dash'] ), opacity=self.plot_properties['opacity'] )] elif self.plot_type == 'box': # flip the variables according to the box orientation if self.plot_properties['box_orientation'] == 'h': self.plot_properties['x'], self.plot_properties['y'] = self.plot_properties['y'], self.plot_properties['x'] self.trace = [go.Box( x=self.plot_properties['x'], y=self.plot_properties['y'], name=self.plot_properties['name'], customdata=self.plot_properties['custom'], boxmean=self.plot_properties['box_stat'], orientation=self.plot_properties['box_orientation'], boxpoints=self.plot_properties['box_outliers'], fillcolor=self.plot_properties['in_color'], line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ), opacity=self.plot_properties['opacity'] )] elif self.plot_type == 'bar': if self.plot_properties['box_orientation'] == 'h': self.plot_properties['x'], self.plot_properties['y'] = self.plot_properties['y'], self.plot_properties['x'] self.trace = [go.Bar( x=self.plot_properties['x'], y=self.plot_properties['y'], name=self.plot_properties['name'], ids=self.plot_properties['featureBox'], customdata=self.plot_properties['custom'], orientation=self.plot_properties['box_orientation'], marker=dict( color=self.plot_properties['in_color'], colorscale=self.plot_properties['colorscale_in'], showscale=self.plot_properties['show_colorscale_legend'], reversescale=self.plot_properties['invert_color_scale'], colorbar=dict( len=0.8 ), line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ) ), opacity=self.plot_properties['opacity'] )] elif self.plot_type == 'histogram': self.trace = [go.Histogram( x=self.plot_properties['x'], y=self.plot_properties['x'], name=self.plot_properties['name'], orientation=self.plot_properties['box_orientation'], nbinsx=self.plot_properties['bins'], nbinsy=self.plot_properties['bins'], marker=dict( color=self.plot_properties['in_color'], line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ) ), histnorm=self.plot_properties['normalization'], opacity=self.plot_properties['opacity'], cumulative=dict( enabled=self.plot_properties['cumulative'], direction=self.plot_properties['invert_hist'] ) )] elif self.plot_type == 'pie': self.trace = [go.Pie( labels=self.plot_properties['x'], values=self.plot_properties['y'], name=self.plot_properties['custom'][0], )] elif self.plot_type == '2dhistogram': self.trace = [go.Histogram2d( x=self.plot_properties['x'], y=self.plot_properties['y'], colorscale=self.plot_properties['color_scale'] )] elif self.plot_type == 'polar': self.trace = [go.Scatterpolar( r=self.plot_properties['y'], theta=self.plot_properties['x'], mode=self.plot_properties['marker'], name=self.plot_properties['y_name'], marker=dict( color=self.plot_properties['in_color'], size=self.plot_properties['marker_size'], symbol=self.plot_properties['marker_symbol'], line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ) ), line=dict( color=self.plot_properties['in_color'], width=self.plot_properties['marker_width'], dash=self.plot_properties['line_dash'] ), opacity=self.plot_properties['opacity'], )] elif self.plot_type == 'ternary': # prepare the hover text to display if the additional combobox is empty or not # this setting is necessary to overwrite the standard hovering labels if self.plot_properties['additional_hover_text'] == []: text = [self.plot_properties['x_name'] + ': {}'.format(self.plot_properties['x'][k]) + '<br>{}: {}'.format(self.plot_properties['y_name'], self.plot_properties['y'][k]) + '<br>{}: {}'.format(self.plot_properties['z_name'], self.plot_properties['z'][k]) for k in range(len(self.plot_properties['x']))] else: text = [self.plot_properties['x_name'] + ': {}'.format(self.plot_properties['x'][k]) + '<br>{}: {}'.format(self.plot_properties['y_name'], self.plot_properties['y'][k]) + '<br>{}: {}'.format(self.plot_properties['z_name'], self.plot_properties['z'][k]) + '<br>{}'.format(self.plot_properties['additional_hover_text'][k]) for k in range(len(self.plot_properties['x']))] self.trace = [go.Scatterternary( a=self.plot_properties['x'], b=self.plot_properties['y'], c=self.plot_properties['z'], name=self.plot_properties['x_name'] + ' + ' + self.plot_properties['y_name'] + ' + ' + self.plot_properties['z_name'], hoverinfo='text', text=text, mode='markers', marker=dict( color=self.plot_properties['in_color'], colorscale=self.plot_properties['colorscale_in'], showscale=self.plot_properties['show_colorscale_legend'], reversescale=self.plot_properties['invert_color_scale'], colorbar=dict( len=0.8 ), size=self.plot_properties['marker_size'], symbol=self.plot_properties['marker_symbol'], line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ) ), opacity=self.plot_properties['opacity'] )] elif self.plot_type == 'contour': self.trace = [go.Contour( z=[self.plot_properties['x'], self.plot_properties['y']], contours=dict( coloring=self.plot_properties['cont_type'], showlines=self.plot_properties['show_lines'] ), colorscale=self.plot_properties['color_scale'], opacity=self.plot_properties['opacity'] )] elif self.plot_type == 'violin': # flip the variables according to the box orientation if self.plot_properties['box_orientation'] == 'h': self.plot_properties['x'], self.plot_properties['y'] = self.plot_properties['y'], self.plot_properties['x'] self.trace = [go.Violin( x=self.plot_properties['x'], y=self.plot_properties['y'], name=self.plot_properties['name'], customdata=self.plot_properties['custom'], orientation=self.plot_properties['box_orientation'], points=self.plot_properties['box_outliers'], fillcolor=self.plot_properties['in_color'], line=dict( color=self.plot_properties['out_color'], width=self.plot_properties['marker_width'] ), opacity=self.plot_properties['opacity'], meanline=dict( visible=self.plot_properties['show_mean_line'] ), side=self.plot_properties['violin_side'] )] return self.trace
def data_graph( df, filename, chart_type, xaxis_type, yaxis_type, ): """アップロードされたデータのグラフを描画""" basename = os.path.splitext(filename)[0] # ファイル名の1つ目の'_'で区切って、グラフタイトルとY軸名に分ける if '_' in basename: title, yaxis_name = basename.split('_', 1) # ファイル名に'_'がなければグラフタイトル、Y軸名ともにファイル名 else: title, yaxis_name = basename, basename def args(i): """graph_objs helper func""" return {'x': df.index, 'y': df[i], 'name': i} # チャートの種類をディクショナリで分岐 # 内包表記でdfの列の数だけトレース data = { 'Line': [go.Scatter(args(i)) for i in df.columns], 'Bar': [go.Bar(args(i)) for i in df.columns], 'Histogram': [go.Histogram(x=df[i], name=i, opacity=.5) for i in df.columns], 'Pie': [ go.Pie(labels=df.index, values=df[i], name=i, domain={'column': list(df.columns).index(i)}) for i in df.columns ], 'Polar': [ go.Scatterpolar( r=df[i], theta=df.index, name=i, ) for i in df.columns ], 'Heatmap': [go.Heatmap(x=df.index, y=df.columns, z=df.values)], 'Box': [go.Box(y=df[i], name=i) for i in df.columns], # 'Contour': [go.Contour(x=df.index, y=df.columns, z=df.values)] '3D Scatter': [ go.Scatter3d(x=df.index, y=df.columns, z=df[i], name=i) for i in df.columns ], '3D Surface': [ go.Surface(x=df.index, y=df.columns, z=df.values, name=yaxis_name, contours=go.surface.Contours( z=go.surface.contours.Z(show=True, usecolormap=True, highlightcolor="#42f462", project=dict(z=True)))), ], '2D Histogram': [go.Histogram2d(x=df.iloc[:, 0], y=df.iloc[:, 1])] } # チャートの種類でレイアウトを分岐 # 分岐にはdefaultdictを使い、デフォルトはlambda式で返す layout = defaultdict( # default layout lambda: go.Layout(title=go.layout.Title(text=title), xaxis={ 'type': xaxis_type, 'title': df.index.name, 'rangeslider': dict(visible=False), }, yaxis={ 'type': yaxis_type, 'title': yaxis_name, }, margin={ 'l': 60, 'b': 50 }, hovermode='closest'), # other layout { 'Histogram': go.Layout(title=title, xaxis={'title': 'Value'}, yaxis={'title': 'Count'}, barmode='overlay', hovermode='closest'), 'Pie': go.Layout(title=go.layout.Title(text=title), grid={ 'columns': len(df.columns) - 1, 'rows': 1 }, hovermode='closest') }) return dcc.Graph(id='the_graph', figure={ 'data': data[chart_type], 'layout': layout[chart_type] })