Ejemplo n.º 1
0
 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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
def _to_iplot(self,colors=None,colorscale=None,kind='scatter',mode='lines',symbol='dot',size='12',fill=False,
		width=3,dash='solid',sortbars=False,keys=False,bestfit=False,bestfit_colors=None,
		mean=False,mean_colors=None,asDates=False,asTimestamp=False,text=None,**kwargs):
	"""
	Generates a plotly Data object 

	Parameters
	----------
		colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		colorscale : str 
			Color scale name
			Only valid if 'colors' is null
			See cufflinks.colors.scales() for available scales
		kind : string
			Kind of chart
				scatter
				bar
		mode : string
			Plotting mode for scatter trace
				lines
				markers
				lines+markers
				lines+text
				markers+text
				lines+markers+text		
		symbol : string
			The symbol that is drawn on the plot for each marker
			Valid only when mode includes markers
				dot
				cross
				diamond
				square
				triangle-down
				triangle-left
				triangle-right
				triangle-up
				x
		size : string or int 
			Size of marker 
			Valid only if marker in mode
		fill : bool
			Filled Traces
		width : int
			Line width
		dash : string
			Drawing style of lines
				solid
				dash
				dashdot
				dot
		sortbars : bool
			Sort bars in descending order
			* Only valid when kind='bar'
		keys : list of columns
			List of columns to chart.
			Also can be usded for custom sorting.
		bestfit : boolean or list
			If True then a best fit line will be generated for 
			all columns. 
			If list then a best fit line will be generated for 
			each key on the list. 
		bestfit_colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		asDates : bool
			If true it forces truncates times from a DatetimeIndex
		
	""" 
	df=self.copy()

	if asTimestamp:
		x=[_ for _ in df.index]
	elif df.index.__class__.__name__ in ('PeriodIndex','DatetimeIndex'):
		if asDates:
			df.index=df.index.date
		x=df.index.format()
	elif isinstance(df.index,pd.MultiIndex):
		x=['({0})'.format(','.join(_)) for _ in df.index.values]
	else:
		x = df.index.values
	lines={}
	if type(df)==pd.core.series.Series:
		df=pd.DataFrame({df.name:df})

	if not keys:		
		if 'bar' in kind:
			if sortbars:
				keys=df.sum().sort(inplace=False,ascending=False).keys()
			else:
				keys=df.keys()
		else:
			keys=df.keys()
	colors=get_colors(colors,colorscale,keys)
	for key in keys:
		lines[key]={}
		lines[key]["x"]=x
		lines[key]["y"]=df[key].fillna('').values
		lines[key]["name"]=key
		if text is not None:
			lines[key]["text"]=text
		if 'bar' in kind:
			lines[key]["marker"]={'color':to_rgba(colors[key],.6),'line':{'color':colors[key],'width':1}}
		else:
			lines[key]["line"]={'color':colors[key],'width':width,'dash':dash}
			lines[key]["mode"]=mode
			if 'marker' in mode:
				lines[key]["marker"]=Marker(symbol=symbol,size=size)
			if fill:
				lines[key]["fill"]='tonexty' if kind=='area' else 'tozeroy'
				lines[key]["fillcolor"]=to_rgba(colors[key],kwargs['opacity'] if 'opacity' in kwargs else .3		)
	if 'bar' in kind:
		lines_plotly=[Bar(lines[key]) for key in keys]
	else:
		lines_plotly=[Scatter(lines[key]) for key in keys]
	for trace in lines_plotly:
		if isinstance(trace['name'],pd.tslib.Timestamp):
			trace.update(name=str(trace['name']))

	if bestfit:
		if type(bestfit)==list:
			keys=bestfit
		d={}
		for key in keys:
			bestfit=df[key].bestfit()
			d[bestfit.formula]=bestfit
		bestfit_lines=pd.DataFrame(d).to_iplot(bestfit=False,colors=bestfit_colors,kind='scatter',asTimestamp=asTimestamp)
		for line in bestfit_lines:
			line['line']['dash']='dash'
			if not bestfit_colors:
				line['line']['color']=to_rgba(line['line']['color'],.6)
		data=Data(lines_plotly)
		data.extend(bestfit_lines)
		return data

	if mean:
		if type(mean)==list:
			keys=mean
		d={}
		for key in keys:
			mean=df[key].mean()
			d['MEAN({key})'.format(key=key)]=pd.Series([mean]*len(df[key]),index=df[key].index)
		mean_lines=pd.DataFrame(d).to_iplot(mean=False,colors=mean_colors,kind='scatter',asTimestamp=asTimestamp)
		for line in mean_lines:
			line['line']['dash']='dash'
			if not mean_colors:
				line['line']['color']=to_rgba(line['line']['color'],.6)
		data=Data(lines_plotly)
		data.extend(mean_lines)
		return data
	return Data(lines_plotly)
Ejemplo n.º 4
0
def _to_iplot(self,colors=None,colorscale=None,kind='scatter',mode='lines',symbol='dot',size='12',fill=False,
		width=3,sortbars=False,keys=False,bestfit=False,bestfit_colors=None,asDates=False,**kwargs):
	"""
	Generates a plotly Data object 

	Parameters
	----------
		colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		colorscale : str 
			Color scale name
			Only valid if 'colors' is null
			See cufflinks.colors.scales() for available scales
		kind : string
			Kind of chart
				scatter
				bar
		mode : string
			Plotting mode for scatter trace
				lines
				markers
				lines+markers
				lines+text
				markers+text
				lines+markers+text		
		symbol : string
			The symbol that is drawn on the plot for each marker
			Valid only when mode includes markers
				dot
				cross
				diamond
				square
				triangle-down
				triangle-left
				triangle-right
				triangle-up
				x
		size : string or int 
			Size of marker 
			Valid only if marker in mode
		fill : bool
			Filled Traces
		width : int
			Line width
		sortbars : bool
			Sort bars in descending order
			* Only valid when kind='bar'
		keys : list of columns
			List of columns to chart.
			Also can be usded for custom sorting.
		bestfit : boolean or list
			If True then a best fit line will be generated for 
			all columns. 
			If list then a best fit line will be generated for 
			each key on the list. 
		bestfit_colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		asDates : bool
			If true it forces truncates times from a DatetimeIndex
		
	""" 
	df=self.copy()
	if df.index.__class__.__name__ in ('PeriodIndex','DatetimeIndex'):
		if asDates:
			df.index=df.index.date
		x=df.index.format()
	else:
		x = df.index.values
	lines={}
	if type(df)==pd.core.series.Series:
		df=pd.DataFrame({df.name:df})
	if not keys:		
		if kind=='bar':
			if sortbars:
				keys=df.sum().sort(inplace=False,ascending=False).keys()
			else:
				keys=df.keys()
		else:
			keys=df.keys()
	colors=get_colors(colors,colorscale,keys)
	for key in keys:
		lines[key]={}
		lines[key]["x"]=x
		lines[key]["y"]=df[key].fillna('').values
		lines[key]["name"]=key
		if kind=='bar':
			lines[key]["marker"]={'color':to_rgba(colors[key],.6),'line':{'color':colors[key],'width':1}}
		else:
			lines[key]["line"]={'color':colors[key],'width':width}
			lines[key]["mode"]=mode
			if 'marker' in mode:
				lines[key]["marker"]=Marker(symbol=symbol,size=size)
			if fill:
				lines[key]["fill"]='tozeroy'
				lines[key]["fillcolor"]=to_rgba(colors[key],.3		)
		for k,v in kwargs.items():
			lines[key][k]=v
	if kind=='bar':
		lines_plotly=[Bar(lines[key]) for key in keys]
	else:
		lines_plotly=[lines[key] for key in keys]

	if bestfit:
		if type(bestfit)==list:
			keys=bestfit
		d={}
		for key in keys:
			bestfit=df[key].bestfit()
			d[bestfit.formula]=bestfit
		bestfit_lines=pd.DataFrame(d).to_iplot(bestfit=False,colors=bestfit_colors,kind='scatter')
		for line in bestfit_lines:
			line['line']['dash']='dash'
			if not bestfit_colors:
				line['line']['color']=to_rgba(line['line']['color'],.6)
		data=Data(lines_plotly)
		data.extend(bestfit_lines)
		return data
	return Data(lines_plotly)