def scatterplot(dataframe, headers, diag, size, height, width, title, **kwargs): """ Refer to FigureFactory.create_scatterplotmatrix() for docstring Returns fig for scatterplotmatrix without index """ dim = len(dataframe) fig = make_subplots(rows=dim, cols=dim, print_grid=False) trace_list = [] # Insert traces into trace_list for listy in dataframe: for listx in dataframe: if (listx == listy) and (diag == "histogram"): trace = graph_objs.Histogram(x=listx, showlegend=False) elif (listx == listy) and (diag == "box"): trace = graph_objs.Box(y=listx, name=None, showlegend=False) else: if "marker" in kwargs: kwargs["marker"]["size"] = size trace = graph_objs.Scatter(x=listx, y=listy, mode="markers", showlegend=False, **kwargs) trace_list.append(trace) else: trace = graph_objs.Scatter(x=listx, y=listy, mode="markers", marker=dict(size=size), showlegend=False, **kwargs) trace_list.append(trace) 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]) fig["layout"].update(height=height, width=width, title=title, showlegend=True) hide_tick_labels_from_box_subplots(fig) return fig
def create_2d_density(x, y, colorscale='Earth', ncontours=20, hist_color=(0, 0, 0.5), point_color=(0, 0, 0.5), point_size=2, title='2D Density Plot', height=600, width=600): """ Returns figure for a 2D density plot :param (list|array) x: x-axis data for plot generation :param (list|array) y: y-axis data for plot generation :param (str|tuple|list) colorscale: either a plotly scale name, an rgb or hex color, a color tuple or a list or tuple of colors. An rgb color is of the form 'rgb(x, y, z)' where x, y, z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colormap is a list, it must contain the valid color types aforementioned as its members. :param (int) ncontours: the number of 2D contours to draw on the plot :param (str) hist_color: the color of the plotted histograms :param (str) point_color: the color of the scatter points :param (str) point_size: the color of the scatter points :param (str) title: set the title for the plot :param (float) height: the height of the chart :param (float) width: the width of the chart Example 1: Simple 2D Density Plot ``` import plotly.plotly as py from plotly.figure_factory create_2d_density import numpy as np # Make data points 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)) # Create a figure fig = create_2D_density(x, y) # Plot the data py.iplot(fig, filename='simple-2d-density') ``` Example 2: Using Parameters ``` import plotly.plotly as py from plotly.figure_factory create_2d_density import numpy as np # Make data points 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)) # Create custom colorscale colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2), (0.98,0.98,0.98)] # Create a figure fig = create_2D_density( x, y, colorscale=colorscale, hist_color='rgb(255, 237, 222)', point_size=3) # Plot the data py.iplot(fig, filename='use-parameters') ``` """ # validate x and y are filled with numbers only for array in [x, y]: if not all(isinstance(element, Number) for element in array): raise exceptions.PlotlyError( "All elements of your 'x' and 'y' lists must be numbers." ) # validate x and y are the same length if len(x) != len(y): raise exceptions.PlotlyError( "Both lists 'x' and 'y' must be the same length." ) colorscale = utils.validate_colors(colorscale, 'rgb') colorscale = make_linear_colorscale(colorscale) # validate hist_color and point_color hist_color = utils.validate_colors(hist_color, 'rgb') point_color = utils.validate_colors(point_color, 'rgb') trace1 = graph_objs.Scatter( x=x, y=y, mode='markers', name='points', marker=dict( color=point_color[0], size=point_size, opacity=0.4 ) ) trace2 = graph_objs.Histogram2dContour( x=x, y=y, name='density', ncontours=ncontours, colorscale=colorscale, reversescale=True, showscale=False ) trace3 = graph_objs.Histogram( x=x, name='x density', marker=dict(color=hist_color[0]), yaxis='y2' ) trace4 = graph_objs.Histogram( y=y, name='y density', marker=dict(color=hist_color[0]), xaxis='x2' ) data = [trace1, trace2, trace3, trace4] layout = graph_objs.Layout( showlegend=False, autosize=False, title=title, height=height, width=width, 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 = graph_objs.Figure(data=data, layout=layout) return fig
def create_2d_density( x, y, colorscale="Earth", ncontours=20, hist_color=(0, 0, 0.5), point_color=(0, 0, 0.5), point_size=2, title="2D Density Plot", height=600, width=600, ): """ **deprecated**, use instead :func:`plotly.express.density_heatmap`. :param (list|array) x: x-axis data for plot generation :param (list|array) y: y-axis data for plot generation :param (str|tuple|list) colorscale: either a plotly scale name, an rgb or hex color, a color tuple or a list or tuple of colors. An rgb color is of the form 'rgb(x, y, z)' where x, y, z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colormap is a list, it must contain the valid color types aforementioned as its members. :param (int) ncontours: the number of 2D contours to draw on the plot :param (str) hist_color: the color of the plotted histograms :param (str) point_color: the color of the scatter points :param (str) point_size: the color of the scatter points :param (str) title: set the title for the plot :param (float) height: the height of the chart :param (float) width: the width of the chart Examples -------- Example 1: Simple 2D Density Plot >>> from plotly.figure_factory import create_2d_density >>> import numpy as np >>> # Make data points >>> 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)) >>> # Create a figure >>> fig = create_2d_density(x, y) >>> # Plot the data >>> fig.show() Example 2: Using Parameters >>> from plotly.figure_factory import create_2d_density >>> import numpy as np >>> # Make data points >>> 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)) >>> # Create custom colorscale >>> colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', ... (1, 1, 0.2), (0.98,0.98,0.98)] >>> # Create a figure >>> fig = create_2d_density(x, y, colorscale=colorscale, ... hist_color='rgb(255, 237, 222)', point_size=3) >>> # Plot the data >>> fig.show() """ # validate x and y are filled with numbers only for array in [x, y]: if not all(isinstance(element, Number) for element in array): raise plotly.exceptions.PlotlyError( "All elements of your 'x' and 'y' lists must be numbers.") # validate x and y are the same length if len(x) != len(y): raise plotly.exceptions.PlotlyError( "Both lists 'x' and 'y' must be the same length.") colorscale = clrs.validate_colors(colorscale, "rgb") colorscale = make_linear_colorscale(colorscale) # validate hist_color and point_color hist_color = clrs.validate_colors(hist_color, "rgb") point_color = clrs.validate_colors(point_color, "rgb") trace1 = graph_objs.Scatter( x=x, y=y, mode="markers", name="points", marker=dict(color=point_color[0], size=point_size, opacity=0.4), ) trace2 = graph_objs.Histogram2dContour( x=x, y=y, name="density", ncontours=ncontours, colorscale=colorscale, reversescale=True, showscale=False, ) trace3 = graph_objs.Histogram(x=x, name="x density", marker=dict(color=hist_color[0]), yaxis="y2") trace4 = graph_objs.Histogram(y=y, name="y density", marker=dict(color=hist_color[0]), xaxis="x2") data = [trace1, trace2, trace3, trace4] layout = graph_objs.Layout( showlegend=False, autosize=False, title=title, height=height, width=width, 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 = graph_objs.Figure(data=data, layout=layout) return fig
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 scatterplot_dict(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. Used if colormap is a dictionary with index values as keys pointing to colors. Forces colormap_type to behave categorically because it would not make sense colors are assigned to each index value and thus implies that a categorical approach should be taken """ 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] = [] # 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[name]), showlegend=True ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=new_listx, name=None, marker=dict( color=theme[name]), showlegend=True ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size kwargs['marker']['color'] = theme[name] 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[name]), 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[name]), showlegend=False ) elif (listx == listy) and (diag == 'box'): trace = graph_objs.Box( y=new_listx, name=None, marker=dict( color=theme[name]), showlegend=False ) else: if 'marker' in kwargs: kwargs['marker']['size'] = size kwargs['marker']['color'] = theme[name] 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[name]), showlegend=False, **kwargs ) # Push the trace into dictionary unique_index_vals[name] = trace 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 else: fig['layout'].update( height=height, width=width, title=title, showlegend=True) return fig