def get_subplots(figures): shape=(len(figures),1) layout=tools.get_base_layout(figures) subplots=tools.subplots(figures,shape=shape,shared_xaxes=True,base_layout=layout) if len(figures)==2: subplots['layout']['yaxis1']['domain']=[.27,1.0] subplots['layout']['yaxis2']['domain']=[0,.25] return subplots
def _iplot(self,data=None,layout=None,filename='',sharing=None, kind='scatter',title='',xTitle='',yTitle='',zTitle='',theme=None,colors=None,colorscale=None,fill=False,width=None, dash='solid',mode='lines',symbol='dot',size=12,barmode='',sortbars=False,bargap=None,bargroupgap=None,bins=None,histnorm='', histfunc='count',orientation='v',boxpoints=False,annotations=None,keys=False,bestfit=False, bestfit_colors=None,mean=False,mean_colors=None,categories='',x='',y='',z='',text='',gridcolor=None, zerolinecolor=None,margin=None,labels=None,values=None,secondary_y='',subplots=False,shape=None,error_x=None, error_y=None,error_type='data',asFrame=False,asDates=False,asFigure=False, asImage=False,dimensions=(1116,587),asPlot=False,asUrl=False,online=None,**kwargs): """ Returns a plotly chart either as inline chart, image of Figure object Parameters: ----------- data : Data Plotly Data Object. If not entered then the Data object will be automatically generated from the DataFrame. data : Data Plotly Data Object. If not entered then the Data object will be automatically generated from the DataFrame. layout : Layout Plotly layout Object If not entered then the Layout objet will be automatically generated from the DataFrame. filename : string Filename to be saved as in plotly account sharing : string Sets the sharing level permission public - anyone can see this chart private - only you can see this chart secret - only people with the link can see the chart kind : string Kind of chart scatter bar box spread ratio heatmap surface histogram bubble bubble3d scatter3d title : string Chart Title xTitle : string X Axis Title yTitle : string Y Axis Title zTitle : string zTitle : string Z Axis Title Applicable only for 3d charts theme : string Layout Theme solar pearl white see cufflinks.getThemes() for all available themes 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 If the color name is preceded by a minus (-) then the scale is inversed Only valid if 'colors' is null See cufflinks.colors.scales() for available scales fill : bool Filled Traces width : int Line width dash : string Drawing style of lines solid dash dashdot dot 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 barmode : string Mode when displaying bars group stack overlay * Only valid when kind='bar' sortbars : bool Sort bars in descending order * Only valid when kind='bar' bargap : float Sets the gap between bars [0,1) * Only valid when kind is 'histogram' or 'bar' bargroupgap : float Set the gap between groups [0,1) * Only valid when kind is 'histogram' or 'bar' bins : int Specifies the number of bins * Only valid when kind='histogram' histnorm : string '' (frequency) percent probability density probability density Sets the type of normalization for an histogram trace. By default the height of each bar displays the frequency of occurrence, i.e., the number of times this value was found in the corresponding bin. If set to 'percent', the height of each bar displays the percentage of total occurrences found within the corresponding bin. If set to 'probability', the height of each bar displays the probability that an event will fall into the corresponding bin. If set to 'density', the height of each bar is equal to the number of occurrences in a bin divided by the size of the bin interval such that summing the area of all bins will yield the total number of occurrences. If set to 'probability density', the height of each bar is equal to the number of probability that an event will fall into the corresponding bin divided by the size of the bin interval such that summing the area of all bins will yield 1. * Only valid when kind='histogram' histfunc : string count sum avg min max Sets the binning function used for an histogram trace. * Only valid when kind='histogram' orientation : string h v Sets the orientation of the bars. If set to 'v', the length of each | bar will run vertically. If set to 'h', the length of each bar will | run horizontally * Only valid when kind is 'histogram','bar' or 'box' boxpoints : string Displays data points in a box plot outliers all suspectedoutliers False annotations : dictionary Dictionary of annotations {x_point : text} 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 categories : string Name of the column that contains the categories x : string Name of the column that contains the x axis values y : string Name of the column that contains the y axis values z : string Name of the column that contains the z axis values text : string Name of the column that contains the text values 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 labels : string Name of the column that contains the labels. * Only valid when kind='pie' values : string Name of the column that contains the values. * Only valid when kind='pie' secondary_y : string or list(string) Name(s) of the column to be charted on the right hand side axis subplots : bool If true then each trace is placed in subplot layout shape : (rows,cols) Tuple indicating the size of rows and columns If omitted then the layout is automatically set * Only valid when subplots=True error_x : int or float or [int or float] error values for the x axis error_y : int or float or [int or float] error values for the y axis error_type : string type of error bars 'data' 'constant' 'percent' 'sqrt' 'continuous' 'continuous_percent' asFrame : bool If true then the data component of Figure will be of Pandas form (Series) otherwise they will be index values asDates : bool If true it truncates times from a DatetimeIndex asFigure : bool If True returns plotly Figure asImage : bool If True it returns Image * Only valid when asImage=True dimensions : tuple(int,int) Dimensions for image (width,height) asPlot : bool If True the chart opens in browser asUrl : bool If True the chart url is returned. No chart is displayed. online : bool If True then the chart is rendered on the server even when running in offline mode. Other Kwargs ============ Pie charts sort : bool If True it sorts the labels by value pull : float [0-1] Pulls the slices from the centre hole : float [0-1] Sets the size of the inner hole textposition : string Sets the position of the legends for each slice outside inner textinfo : string Sets the information to be displayed on the legends label percent value * or ony combination of the above using '+' between each item ie 'label+percent' Error Bars error_trace : string Name of the column for which error should be plotted. If omitted then errors apply to all traces. error_values_minus : int or float or [int or float] Values corresponding to the span of the error bars below the trace coordinates error_color : string Color for error bars error_thickness : float Sets the line thickness of the error bars error_width : float Sets the width (in pixels) of the cross-bar at both ends of the error bars error_opacity : float [0,1] Opacity for the error bars Subplots horizontal_spacing : float [0,1] Space between subplot columns. vertical_spacing : float [0,1] Space between subplot rows. subplot_titles : bool If True, chart titles are plotted at the top of each subplot shared_xaxes : bool Assign shared x axes. If True, subplots in the same grid column have one common shared x-axis at the bottom of the grid. shared_yaxes : bool Assign shared y axes. If True, subplots in the same grid row have one common shared y-axis on the left-hand side of the grid. 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 """ # Look for invalid kwargs valid_kwargs = ['color','opacity','column','columns','labels','text','world_readable'] PIE_KWARGS=['sort','pull','hole','textposition','textinfo','linecolor'] OHLC_KWARGS=['up_color','down_color'] SUBPLOT_KWARGS=['horizontal_spacing', 'vertical_spacing', 'specs', 'insets','start_cell','shared_xaxes','shared_yaxes','subplot_titles'] ERROR_KWARGS=['error_trace','error_values_minus','error_color','error_thickness', 'error_width','error_opacity'] kwargs_list = [tools.__LAYOUT_KWARGS,OHLC_KWARGS,PIE_KWARGS,SUBPLOT_KWARGS,ERROR_KWARGS] [valid_kwargs.extend(_) for _ in kwargs_list] for key in kwargs.keys(): if key not in valid_kwargs: raise Exception("Invalid keyword : '{0}'".format(key)) # Setting default values if not colors: colors=kwargs['color'] if 'color' in kwargs else colors if isinstance(colors,str): colors=[colors] opacity=kwargs['opacity'] if 'opacity' in kwargs else 0.8 # Get values from config theme if theme is None: theme = auth.get_config_file()['theme'] theme_config=tools.getTheme(theme) if colorscale is None: colorscale=theme_config['colorscale'] if 'colorscale' in theme_config else 'dflt' if width is None: if kind != 'pie': width=theme_config['linewidth'] if 'linewidth' in theme_config else 2 # if bargap is None: # bargap=theme_config['bargap'] if 'bargap' in theme_config else 0 # In case column was used instead of keys if 'column' in kwargs: keys=[kwargs['column']] if isinstance(kwargs['column'],str) else kwargs['column'] if 'columns' in kwargs: keys=[kwargs['columns']] if isinstance(kwargs['columns'],str) else kwargs['columns'] kind='line' if kind=='lines' else kind # We assume we are good citizens validate=True if not layout: l_kwargs=dict([(k,kwargs[k]) for k in tools.__LAYOUT_KWARGS if k in kwargs]) if annotations: annotations=getAnnotations(self.copy(),annotations) layout=tools.getLayout(theme=theme,xTitle=xTitle,yTitle=yTitle,zTitle=zTitle,title=title,barmode=barmode, bargap=bargap,bargroupgap=bargroupgap,annotations=annotations,gridcolor=gridcolor, zerolinecolor=zerolinecolor,margin=margin,is3d='3d' in kind,**l_kwargs) if not data: if categories: data=Data() if 'bar' in kind: df=self.copy() df=df.set_index(categories) fig=df.figure(kind=kind,colors=colors,colorscale=colorscale,fill=fill,width=width,sortbars=sortbars, asDates=asDates,mode=mode,symbol=symbol,size=size,text=text,barmode=barmode,orientation=orientation) data=fig['data'] else: _keys=pd.unique(self[categories]) colors=get_colors(colors,colorscale,_keys) mode='markers' if 'markers' not in mode else mode for _ in _keys: __=self[self[categories]==_].copy() if text: _text=__[text] if asFrame else __[text].values _x=__[x] if asFrame else __[x].values _y=__[y] if asFrame else __[y].values if z: _z=__[z] if asFrame else __[z].values if 'bubble' in kind: rg=__[size].values rgo=self[size].values _size=[int(100*(float(i)-rgo.min())/(rgo.max()-rgo.min()))+12 for i in rg] else: _size=size _data=Scatter3d(x=_x,y=_y,mode=mode,name=_, marker=Marker(color=colors[_],symbol=symbol,size=_size,opacity=opacity, line=Line(width=width)),textfont=tools.getLayout(theme=theme)['xaxis1']['titlefont']) if '3d' in kind: _data=Scatter3d(x=_x,y=_y,z=_z,mode=mode,name=_, marker=Marker(color=colors[_],symbol=symbol,size=_size,opacity=opacity, line=Line(width=width)),textfont=tools.getLayout(theme=theme)['xaxis1']['titlefont']) else: _data=Scatter(x=_x,y=_y,mode=mode,name=_, marker=Marker(color=colors[_],symbol=symbol,size=_size,opacity=opacity, line=Line(width=width)),textfont=tools.getLayout(theme=theme)['xaxis1']['titlefont']) if text: _data.update(text=_text) data.append(_data) else: if kind in ('scatter','spread','ratio','bar','barh','area','line'): df=self.copy() if type(df)==pd.core.series.Series: df=pd.DataFrame({df.name:df}) if x: df=df.set_index(x) if y: df=df[y] if kind=='area': df=df.transpose().fillna(0).cumsum().transpose() if text: if not isinstance(text,list): text=self[text].values data=df.to_iplot(colors=colors,colorscale=colorscale,kind=kind,fill=fill,width=width,dash=dash,sortbars=sortbars,keys=keys, bestfit=bestfit,bestfit_colors=bestfit_colors,mean=mean,mean_colors=mean_colors,asDates=asDates,mode=mode,symbol=symbol,size=size, text=text,**kwargs) if kind in ('spread','ratio'): if kind=='spread': trace=self.apply(lambda x:x[0]-x[1],axis=1) positive=trace.apply(lambda x:x if x>=0 else pd.np.nan) negative=trace.apply(lambda x:x if x<0 else pd.np.nan) trace=pd.DataFrame({'positive':positive,'negative':negative}) trace=trace.to_iplot(colors={'positive':'green','negative':'red'},width=0.5) else: trace=self.apply(lambda x:x[0]*1.0/x[1],axis=1).to_iplot(colors=['green'],width=1) trace.update({'xaxis':'x2','yaxis':'y2','fill':'tozeroy', 'name':kind.capitalize(),'connectgaps':False,'showlegend':False}) data.append(Scatter(trace[0])) if kind=='spread': data.append(Scatter(trace[1])) layout['yaxis1'].update({'domain':[.3,1]}) layout['yaxis2']=copy.deepcopy(layout['yaxis1']) layout['xaxis2']=copy.deepcopy(layout['xaxis1']) layout['yaxis2'].update(domain=[0,.25],title=kind.capitalize()) layout['xaxis2'].update(anchor='y2',showticklabels=False) layout['hovermode']='x' if 'bar' in kind: if 'stack' in barmode: layout['legend'].update(traceorder='normal') orientation = 'h' if kind=='barh' else orientation for trace in data: trace.update(orientation=orientation) if kind=='barh': trace['x'],trace['y']=trace['y'],trace['x'] elif kind=='bubble': mode='markers' if 'markers' not in mode else mode x=self[x].values.tolist() y=self[y].values.tolist() z=size if size else z rg=self[z].values z=[int(100*(float(_)-rg.min())/(rg.max()-rg.min()))+12 for _ in rg] text=kwargs['labels'] if 'labels' in kwargs else text labels=self[text].values.tolist() if text else '' clrs=colors if colors else get_scales(colorscale) clrs=[clrs] if not isinstance(clrs,list) else clrs clrs=[clrs[0]]*len(x) marker=Marker(color=clrs,size=z,symbol=symbol, line=Line(width=width),textfont=tools.getLayout(theme=theme)['xaxis1']['titlefont']) trace=Scatter(x=x,y=y,marker=marker,mode='markers',text=labels) data=Data([trace]) elif kind in ('box','histogram','hist'): if isinstance(self,pd.core.series.Series): df=pd.DataFrame({self.name:self}) else: df=self.copy() data=Data() clrs=get_colors(colors,colorscale,df.columns) if 'hist' in kind: barmode = 'overlay' if barmode=='' else barmode layout.update(barmode=barmode) columns=keys if keys else df.columns for _ in columns: if kind=='box': __=Box(y=df[_].values.tolist(),marker=Marker(color=clrs[_]),name=_, line=Line(width=width),boxpoints=boxpoints) else: __=Histogram(x=df[_].values.tolist(),marker=Marker(color=clrs[_]),name=_, line=Line(width=width),orientation=orientation, opacity=kwargs['opacity'] if 'opacity' in kwargs else .8, histfunc=histfunc, histnorm=histnorm) if orientation=='h': __['y']=__['x'] del __['x'] if bins: if orientation=='h': __.update(nbinsy=bins) else: __.update(nbinsx=bins) data.append(__) elif kind in ('heatmap','surface'): x=self[x].values.tolist() if x else self.index.values.tolist() y=self[y].values.tolist() if y else self.columns.values.tolist() z=self[z].values.tolist() if z else self.values.transpose() scale=get_scales('rdbu') if not colorscale else get_scales(colorscale) colorscale=[[float(_)/(len(scale)-1),scale[_]] for _ in range(len(scale))] if kind=='heatmap': data=Data([Heatmap(z=z,x=x,y=y,colorscale=colorscale)]) else: data=Data([Surface(z=z,x=x,y=y,colorscale=colorscale)]) elif kind in ('scatter3d','bubble3d'): data=Data() keys=self[text].values if text else range(len(self)) colors=get_colors(colors,colorscale,keys,asList=True) df=self.copy() df['index']=keys if kind=='bubble3d': rg=self[size].values size=[int(100*(float(_)-rg.min())/(rg.max()-rg.min()))+12 for _ in rg] else: size=[size for _ in range(len(keys))] _data=Scatter3d(x=df[x].values.tolist(),y=df[y].values.tolist(),z=df[z].values.tolist(),mode=mode,name=keys, marker=Marker(color=colors,symbol=symbol,size=size,opacity=.8)) if text: _data.update(text=keys) data.append(_data) elif kind=='pie': labels=self[labels].values.tolist() values=self[values].values.tolist() marker={'colors':get_colors(colors,colorscale,labels,asList=True)} line={} if 'linecolor' in kwargs: line['color']=kwargs['linecolor'] if width: line['width']=width if line: marker['line']=line pie={'type':'pie','values':values,'labels':labels,'name':'', 'marker':marker} for kw in ['sort','pull','hole','textposition','textinfo']: if kw in kwargs: pie[kw]=kwargs[kw] data=Data() del layout['xaxis1'] del layout['yaxis1'] data.append(pie) validate=False elif kind in ['candle','ohlc']: d=tools._ohlc_dict(self) if len(d.keys())!=4: raise Exception("OHLC type of charts require an Open, High, Low and Close column") ohlc_kwargs=check_kwargs(kwargs,OHLC_KWARGS) if kind=='candle': fig=tools.get_candle(self,theme=theme,**ohlc_kwargs) else: fig=tools.get_ohlc(self,theme=theme,**ohlc_kwargs) if bestfit: df=self.copy() bf=_to_iplot(self[d['close']],bestfit=True,bestfit_colors=bestfit_colors,asTimestamp=True) fig['data'].append(bf[1]) data=fig['data'] layout=fig['layout'] ## Sharing Values if all(['world_readable' in kwargs,sharing is None]): sharing=kwargs['world_readable'] if isinstance(sharing,bool): if sharing: sharing='public' else: sharing='private' if sharing is None: sharing=auth.get_config_file()['sharing'] if not filename: if title: filename=title else: filename='Plotly Playground {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")) ## Figure defintion figure=Figure() figure['data']=data figure['layout']=layout ## Check secondary axis if secondary_y: figure=figure.set_axis(secondary_y,side='right') ## Error Bars if kind in ('scatter','bar','barh','lines'): if any([error_x,error_y]): def set_error(axis,**kwargs): return tools.set_errors(figure,axis=axis,**kwargs) kw=check_kwargs(kwargs,ERROR_KWARGS) kw=dict([(k.replace('error_',''),v) for k,v in kw.items()]) kw['type']=error_type if error_x: kw['values']=error_x figure=set_error('x',**kw) if error_y: kw['values']=error_y figure=set_error('y',**kw) ## Subplots if subplots: fig=tools.strip_figures(figure) kw=check_kwargs(kwargs,SUBPLOT_KWARGS) if 'subplot_titles' in kwargs: if kwargs['subplot_titles']==True: kw['subplot_titles']=[d['name'] for d in data] else: kw['subplot_titles']=kwargs['subplot_titles'] figure=tools.subplots(fig,shape,base_layout=layout,theme=theme,**kw) ## Exports validate = False if 'shapes' in layout else validate if asFigure: return figure elif asImage: try: py.image.save_as(figure,filename='img/'+filename,format='png', width=dimensions[0],height=dimensions[1]) path='img/'+filename+'.png' except: py.image.save_as(figure,filename=filename,format='png', width=dimensions[0],height=dimensions[1]) path=filename+'.png' return display(Image(path)) elif asPlot: return py.plot(figure,sharing=sharing,filename=filename,validate=validate) elif asUrl: return py.plot(figure,sharing=sharing,filename=filename,validate=validate,auto_open=False) else: return iplot(figure,sharing=sharing,filename=filename,validate=validate,online=online)
ylabel=r'max $|B|$ [T]') if __name__ == '__main__': from sys import argv columnWidth = 3.28 doubleWidth = 7.0 # 6.68 exampleA = (0.45, 0.35) exampleB = (0.15, 0.35) for filename in argv[1:]: if filename in ("islands.pdf", "Islands.pdf"): print("overview of 3 stability islands in k0,k1 space") fig, ax = subplots(figsize=(columnWidth, 1.2 * columnWidth)) fks = FloquetKSpace(arange(-1, 4.01, 0.05), arange(0, 8.01, 0.05)) fks.solveCxy() fks.plotStability(ax) [ax.spines[dr].set_color(None) for dr in ('top', 'right')] ax.set_xlim((-1, 4.01)) fig.subplots_adjust(top=0.965, bottom=0.115, left=0.115, right=0.97) if filename[0] == 'i': print('truncate to k1 <= 4') fig.set_size_inches(columnWidth, 0.75 * columnWidth) ax.set_ylim((0, 4)) fig.subplots_adjust(top=0.969,