Example #1
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
Example #2
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 '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 '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}
            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')
        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)
Example #3
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 '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 '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}
			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')
		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)