def get_traces(trace, value, type, color=None, width=0.2, opacity=0.3): if "percent" in type: y_up = trace["y"] * (1 + value / 100.00) y_down = trace["y"] * (1 - value / 100.00) else: y_up = trace["y"] + value y_down = trace["y"] - value y = trace["y"] upper = Scatter(y=y_up, mode="lines", showlegend=False, line=Line(width=width), x=trace["x"]) if "yaxis" in trace: upper["yaxis"] = trace["yaxis"] if color: color = normalize(color) else: if "color" in trace["line"]: color = trace["line"]["color"] else: color = "charcoal" upper["line"]["color"] = color lower = upper.copy() name = trace["name"] + "_" if "name" in trace else "" upper.update(name=name + "upper") color = to_rgba(normalize(color), opacity) lower.update(fill="tonexty", fillcolor=color, name=name + "lower", y=y_down) return upper, lower
def get_error_bar(axis="y", type="data", values=None, values_minus=None, color=None, thickness=1, width=5, opacity=1): error = ErrorY() if axis == "y" else ErrorX() if type == "data": if isinstance(values, list) or isinstance(values, np.ndarray): if values_minus: if len(values) != len(values_minus): raise Exception("Array values need to be of same length") error.update(symmetric=False, arrayminus=values_minus) error.update(array=values) else: if values_minus: if isinstance(values_minus, list) or isinstance(a, np.ndarray): raise Exception("Values should be of same type (int, float)") error.udpate(symmetric=False, valueminus=values_minus) error.update(value=values) elif type in ["percent", "constant"]: if isinstance(values, list) or isinstance(values, np.ndarray): raise Exception("Value should be of type (int, float)") error.update(value=values) elif type == "sqrt": pass else: raise Exception("Invalid type: {0}".format(type)) error.update(type=type, thickness=thickness, width=width, visible=True, opacity=opacity) if color: error.update(color=normalize(color)) return error
def zalpha(colors, zs): """Modify the alphas of the color list according to depth""" colors = get_colors(colors,len(zs)) norm = normalize(min(zs),max(zs)) sats = nx.array([1-norm(z)*0.7 for z in zs]) colors = [(c[0],c[1],c[2],c[3]*s) for c,s in zip(colors,sats)] return colors
def zalpha(colors, zs): """Modify the alphas of the color list according to depth""" colors = get_colors(colors, len(zs)) norm = normalize(min(zs), max(zs)) sats = nx.array([1 - norm(z) * 0.7 for z in zs]) colors = [(c[0], c[1], c[2], c[3] * s) for c, s in zip(colors, sats)] return colors
def updateColors(layout): for k,v in layout.items(): if isinstance(v,dict): updateColors(v) else: if 'color' in k.lower(): layout[k]=normalize(v) return layout
def get_ohlc(df, up_color=None, down_color=None, theme=None, **kwargs): ohlc = ["open", "high", "low", "close"] if not theme: theme = auth.get_config_file()["theme"] c_dir = _ohlc_dict(df) args = [df[c_dir[_]] for _ in ohlc] args.append(df.index) fig = py.plotly.tools.FigureFactory.create_ohlc(*args, **kwargs) ohlc_bars = Figure() ohlc_bars["data"] = fig["data"] ohlc_bars["layout"] = fig["layout"] data = ohlc_bars["data"] if up_color: data[0]["line"].update(color=normalize(up_color)) if down_color: data[1]["line"].update(color=normalize(down_color)) ohlc_bars["layout"]["hovermode"] = "closest" layout = getLayout(theme=theme) ohlc_bars["layout"] = merge_dict(layout, ohlc_bars["layout"]) return ohlc_bars
def __init__(self, norm=None, cmap=None): """ norm is a colors.Norm instance to map luminance to 0-1 cmap is a cm colormap instance """ if cmap is None: cmap = get_cmap() if norm is None: norm = colors.normalize() self._A = None self.norm = norm self.cmap = cmap self.observers = []
def updateColors(layout): for k, v in layout.items(): if isinstance(v, dict): updateColors(v) else: if isinstance(v, list): for _ in v: if isinstance(_, dict): updateColors(_) if "color" in k.lower(): if "rgba" not in v: layout[k] = normalize(v) return layout
def plot_surface(self, X, Y, Z, *args, **kwargs): had_data = self.has_data() rows, cols = Z.shape tX,tY,tZ = nx.transpose(X), nx.transpose(Y), nx.transpose(Z) rstride = cbook.popd(kwargs, 'rstride', 10) cstride = cbook.popd(kwargs, 'cstride', 10) # polys = [] boxes = [] for rs in nx.arange(0,rows,rstride): for cs in nx.arange(0,cols,cstride): ps = [] corners = [] for a,ta in [(X,tX),(Y,tY),(Z,tZ)]: ztop = a[rs][cs:min(cols-1,cs+cstride)] zleft = ta[min(cols-1,cs+cstride)][rs:min(rows,rs+rstride+1)] zbase = a[min(rows-1,rs+rstride)][cs:min(cols,cs+cstride+1):] zbase = zbase[::-1] zright = ta[cs][rs:min(rows-1,rs+rstride):] zright = zright[::-1] corners.append([ztop[0],ztop[-1],zbase[0],zbase[-1]]) z = nx.concatenate((ztop,zleft,zbase,zright)) ps.append(z) boxes.append(map(nx.array,zip(*corners))) polys.append(zip(*ps)) # lines = [] shade = [] for box in boxes: n = proj3d.cross(box[0]-box[1], box[0]-box[2]) n = n/proj3d.mod(n)*5 shade.append(nx.dot(n,[-1,-1,0.5])) lines.append((box[0],n+box[0])) # color = nx.array([0,0,1,1]) norm = normalize(min(shade),max(shade)) colors = [color * (0.5+norm(v)*0.5) for v in shade] for c in colors: c[3] = 1 polyc = art3d.Poly3DCollection(polys, facecolors=colors, *args, **kwargs) polyc._zsort = 1 self.add_collection(polyc) # self.auto_scale_xyz(X,Y,Z, had_data) return polyc
def set_norm(self, norm): 'set the colormap for luminance data' if norm is None: norm = colors.normalize() self.norm = norm self.changed()
def set_norm(self, norm): 'set the normalization instance' if norm is None: norm = colors.normalize() self.norm = norm self.changed()
def get_shape( kind="line", x=None, y=None, x0=None, y0=None, x1=None, y1=None, span=0, color="red", dash="solid", width=1, fillcolor=None, fill=False, opacity=1, xref="x", yref="y", ): """ Returns a plotly shape Parameters: ----------- kind : string Shape kind line rect circle x : float x values for the shape. This assumes x0=x1 x0 : float x0 value for the shape x1 : float x1 value for the shape y : float y values for the shape. This assumes y0=y1 y0 : float y0 value for the shape y1 : float y1 value for the shape color : string color for shape line dash : string line style solid dash dashdot dot width : int line width fillcolor : string shape fill color fill : bool If True then fill shape If not fillcolor then the line color will be used opacity : float [0,1] opacity of the fill xref : string Sets the x coordinate system which this object refers to 'x' 'paper' 'x2' etc yref : string Sets the y coordinate system which this object refers to 'y' 'paper' 'y2' etc """ if not x1: if not x0: if not x: xref = "paper" x0 = 0 x1 = 1 else: x0 = x1 = x else: x1 = x0 if not y1: if not y0: if not y: yref = "paper" y0 = 0 y1 = 1 else: y0 = y1 = y else: y1 = y0 shape = { "x0": x0, "y0": y0, "x1": x1, "y1": y1, "line": {"color": normalize(color), "width": width, "dash": dash}, "xref": xref, "yref": yref, } if kind == "line": shape["type"] = "line" elif kind == "circle": shape["type"] = "circle" elif kind == "rect": shape["type"] = "rect" else: raise Exception("Invalid or unkown shape type : {0}".format(kind)) if (fill or fillcolor) and kind != "line": fillcolor = color if not fillcolor else fillcolor fillcolor = to_rgba(normalize(fillcolor), opacity) shape["fillcolor"] = fillcolor return shape
def update_color(n, color): data[n]["fillcolor"] = normalize(color) data[n]["line"].update(color=normalize(color))
def getLayout( theme=None, title="", xTitle="", yTitle="", zTitle="", barmode="", bargap=None, bargroupgap=None, gridcolor=None, zerolinecolor=None, margin=None, annotations=False, is3d=False, **kwargs ): """ Generates a plotly Layout Parameters: ----------- theme : string Layout Theme solar pearl white title : string Chart Title xTitle : string X Axis Title yTitle : string Y Axis Title zTitle : string Z Axis Title Applicable only for 3d charts barmode : string Mode when displaying bars group stack overlay bargap : float Sets the gap between bars [0,1) Applicabe for bar and histogram plots bargroupgap : float Set the gap between groups [0,1) Applicabe for bar and histogram plots gridcolor : string grid color zerolinecolor : string zero line color margin : dict or tuple Dictionary (l,r,b,t) or Tuple containing the left, right, bottom and top margins annotations : dictionary Dictionary of annotations {x_point : text} is3d : bool Indicates if the layout is for a 3D chart Other Kwargs ============ Shapes hline : int, list or dict Draws a horizontal line at the indicated y position(s) Extra parameters can be passed in the form of a dictionary (see shapes) vline : int, list or dict Draws a vertical line at the indicated x position(s) Extra parameters can be passed in the form of a dictionary (see shapes) hline : [y0,y1] Draws a horizontal rectangle at the indicated (y0,y1) positions. Extra parameters can be passed in the form of a dictionary (see shapes) vline : [x0,x1] Draws a vertical rectangle at the indicated (x0,x1) positions. Extra parameters can be passed in the form of a dictionary (see shapes) shapes : dict or list(dict) List of dictionaries with the specifications of a given shape. See help(cufflinks.tools.get_shape) for more information """ for key in kwargs.keys(): if key not in __LAYOUT_KWARGS: raise Exception("Invalid keyword : '{0}'".format(key)) if not theme: theme = auth.get_config_file()["theme"] size = None if annotations: if "font" in annotations: if "size" in annotations["font"]: size = annotations["font"]["size"] def update_annotations(annotations, font_color, arrow_color): if annotations: if isinstance(annotations, dict): annotations = [annotations] for i in annotations: i.update(dict(arrowcolor=arrow_color, font={"color": font_color})) theme_data = getTheme(theme) layout = theme_data["layout"] layout["xaxis1"].update({"title": xTitle}) layout["yaxis1"].update({"title": yTitle}) if annotations: update_annotations(annotations, theme_data["annotations"]["fontcolor"], theme_data["annotations"]["arrowcolor"]) if barmode: layout.update({"barmode": barmode}) if bargroupgap: layout.update({"bargroupgap": bargroupgap}) if bargap: layout.update(bargap=bargap) if title: layout.update({"title": title}) if annotations: if size: annotations["font"]["size"] = size layout.update({"annotations": annotations}) if gridcolor: for k in layout: if "axis" in k: layout[k].update(gridcolor=normalize(gridcolor)) if zerolinecolor: for k in layout: if "axis" in k: layout[k].update(zerolinecolor=normalize(zerolinecolor)) if margin: if isinstance(margin, dict): margin = margin else: margin = dict(zip(("l", "r", "b", "t"), margin)) layout.update(margin=margin) if is3d: if "3d" in theme_data: layout.update(theme_data["3d"]) zaxis = layout["xaxis1"].copy() zaxis.update(title=zTitle) scene = Scene(xaxis=layout["xaxis1"], yaxis=layout["yaxis1"], zaxis=zaxis) layout.update(scene=scene) del layout["xaxis1"] del layout["yaxis1"] ## Kwargs if "legend" in kwargs: layout["showlegend"] = kwargs["legend"] if "logy" in kwargs: if kwargs["logy"]: layout["yaxis1"]["type"] = "log" if "logx" in kwargs: if kwargs["logx"]: layout["xaxis1"]["type"] = "log" # Shapes if any(k in kwargs for k in ["vline", "hline", "shapes", "hspan", "vspan"]): shapes = [] def get_shapes(xline): orientation = xline[0] xline = kwargs[xline] if isinstance(xline, list): for x_i in xline: if isinstance(x_i, dict): x_i["kind"] = "line" shapes.append(get_shape(**x_i)) else: if orientation == "h": shapes.append(get_shape(kind="line", y=x_i)) else: shapes.append(get_shape(kind="line", x=x_i)) elif isinstance(xline, dict): shapes.append(get_shape(**xline)) else: if orientation == "h": shapes.append(get_shape(kind="line", y=xline)) else: shapes.append(get_shape(kind="line", x=xline)) def get_span(xspan): orientation = xspan[0] xspan = kwargs[xspan] if isinstance(xspan, list): for x_i in xspan: if isinstance(x_i, dict): x_i["kind"] = "rect" shapes.append(get_shape(**x_i)) else: v0, v1 = x_i if orientation == "h": shapes.append(get_shape(kind="rect", y0=v0, y1=v1, fill=True, opacity=0.5)) else: shapes.append(get_shape(kind="rect", x0=v0, x1=v1, fill=True, opacity=0.5)) elif isinstance(xspan, dict): xspan["kind"] = "rect" shapes.append(get_shape(**xspan)) elif isinstance(xspan, tuple): v0, v1 = xspan if orientation == "h": shapes.append(get_shape(kind="rect", y0=v0, y1=v1, fill=True, opacity=0.5)) else: shapes.append(get_shape(kind="rect", x0=v0, x1=v1, fill=True, opacity=0.5)) else: raise Exception("Invalid value for {0}span: {1}".format(orientation, xspan)) if "hline" in kwargs: get_shapes("hline") if "vline" in kwargs: get_shapes("vline") if "hspan" in kwargs: get_span("hspan") if "vspan" in kwargs: get_span("vspan") if "shapes" in kwargs: shapes_ = kwargs["shapes"] if isinstance(shapes_, list): for i in shapes_: shp = i if "type" in i else get_shape(**i) shapes.append(shp) elif isinstance(shapes_, dict): shp = shapes_ if "type" in shapes_ else get_shape(**shapes_) shapes.append(shp) else: raise Exception("Shapes need to be either a dict or list of dicts") layout["shapes"] = shapes def updateColors(layout): for k, v in layout.items(): if isinstance(v, dict): updateColors(v) else: if isinstance(v, list): for _ in v: if isinstance(_, dict): updateColors(_) if "color" in k.lower(): if "rgba" not in v: layout[k] = normalize(v) return layout return updateColors(layout)
def getLayout(theme='solar',title='',xTitle='',yTitle='',zTitle='',barmode='', gridcolor=None,zerolinecolor=None,margin=None,annotations=None,is3d=False): """ Generates a plotly Layout Parameters: ----------- theme : string Layout Theme solar pearl white title : string Chart Title xTitle : string X Axis Title yTitle : string Y Axis Title zTitle : string Z Axis Title Applicable only for 3d charts barmode : string Mode when displaying bars group stack overlay gridcolor : string grid color zerolinecolor : string zero line color margin : dict or tuple Dictionary (l,r,b,t) or Tuple containing the left, right, bottom and top margins annotations : dictionary Dictionary of annotations {x_point : text} is3d : bool Indicates if the layout is for a 3D chart """ if theme=='solar': layout=Layout(legend=Legend(bgcolor='charcoal',font={'color':'pearl'}), paper_bgcolor='charcoal',plot_bgcolor='charcoal', yaxis=YAxis(tickfont={'color':'grey12'},gridcolor='grey08',title=yTitle, titlefont={'color':'pearl'},zerolinecolor='grey09'), xaxis=XAxis(tickfont={'color':'grey12'},gridcolor='grey08',title=xTitle, titlefont={'color':'pearl'},zerolinecolor='grey09'), titlefont={'color':'pearl'}) if annotations: annotations.update({'arrowcolor':'grey11','font':{'color':'pearl'}}) elif theme=='pearl': layout=Layout(legend=Legend(bgcolor='pearl02',font={'color':'pearl06'}), paper_bgcolor='pearl02',plot_bgcolor='pearl02', yaxis=YAxis(tickfont={'color':'pearl06'},gridcolor='pearl04' if is3d else 'pearl03',title=yTitle, titlefont={'color':'pearl06'},zeroline=False,zerolinecolor='pearl04' if is3d else 'pearl03'), xaxis=XAxis(tickfont={'color':'pearl06'},gridcolor='pearl04' if is3d else 'pearl03',title=xTitle, titlefont={'color':'pearl06'},zerolinecolor='pearl04' if is3d else 'pearl03')) if annotations: annotations.update({'arrowcolor':'pearl04','font':{'color':'pearl06'}}) elif theme=='white': layout=Layout(legend=Legend(bgcolor='white',font={'color':'pearl06'}), paper_bgcolor='white',plot_bgcolor='white', yaxis=YAxis(tickfont={'color':'pearl06'},gridcolor='pearl04' if is3d else 'pearl03',title=yTitle, titlefont={'color':'pearl06'},zerolinecolor='pearl04' if is3d else 'pearl03'), xaxis=XAxis(tickfont={'color':'pearl06'},gridcolor='pearl04' if is3d else 'pearl03',title=xTitle, titlefont={'color':'pearl06'},zerolinecolor='pearl04' if is3d else 'pearl03')) if annotations: annotations.update({'arrowcolor':'pearl04','font':{'color':'pearl06'}}) if barmode: layout.update({'barmode':barmode}) if title: layout.update({'title':title}) if annotations: layout.update({'annotations':annotations}) if gridcolor: for k in layout: if 'axis' in k: layout[k].update(gridcolor=normalize(gridcolor)) if zerolinecolor: for k in layout: if 'axis' in k: layout[k].update(zerolinecolor=normalize(zerolinecolor)) if margin: if isinstance(margin,dict): margin=margin else: margin=dict(zip(('l','r','b','t'),margin)) layout.update(margin=margin) if is3d: zaxis=layout['xaxis'].copy() zaxis.update(title=zTitle) scene=Scene(xaxis=layout['xaxis'],yaxis=layout['yaxis'],zaxis=zaxis) layout.update(scene=scene) del layout['xaxis'] del layout['yaxis'] def updateColors(layout): for k,v in layout.items(): if isinstance(v,dict): updateColors(v) else: if 'color' in k.lower(): layout[k]=normalize(v) return layout return updateColors(layout)