Package: teeplot
teeplotwrangles your data visualizations out of notebooks for youFree software: MIT licenseInstallation:python3-mpip install teeplotDocumentation:https://github.com/mmore500/teeplot/blob/master/README.rstRepository:https://github.com/mmore500/teeplotteeplot’steefunction can wrap your plotting calls toautomatically manage matplotlib file output, picking meaningful names based on semantic plotting variables.# adapted from https://seaborn.pydata.org/generated/seaborn.FacetGrid.html#seaborn.FacetGridimportseabornassns;fromteeplotimportteeplotastptp.tee(sns.lmplot,# plottersns.load_dataset("tips"),col="time",hue="sex",x="total_bill",y="tip",# fwded kw/argsteeplot_postprocess=sns.FacetGrid.add_legend)# teeplot optionsteepots/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=.pdf
teepots/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=.pngHere’s how it works:teeplot’steefunction that acts as a wrapper around your plotting calls.
Giveteeyour plotting function (e.g.,sns.lineplot) as the first argument and then add the arguments you want to call it with.teeplotautomatically captures the function and its arguments, calls the plotter as instructed, and then it handles the matplotlib file output for you.
It generates descriptive filenames for the saved plots by extracting key information from the plot parameters and arguments.
This feature allows you tokeep track of your visualizations easilyby making the process of saving and cataloging your plots moreefficient,systematicandmeaningful, taking the hassle out of manual file management.teeplotcontains several advanced features, such as adraftmodeflag, which will disable file output globally, and theteeplot_callbackkwarg, which delays plot output to allow for figure tweaks.
Read on for details.ContentsUsage:Example 1|Example 2|Example 3|Example 4|Example 5API:teeplot.tee()|Module-Level Configuration|Environment VariablesCreditsUsageExample 1Simple example demonstrating use withpandasbuilt-in plotting.# adapted from https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.box.htmlimportpandasaspd;fromteeplotimportteeplotastpage_list=[8,10,12,14,72,74,76,78,20,25,30,35,60,85]df=pd.DataFrame({"gender":list("MMMMMMMMFFFFFF"),"age":age_list})tp.tee(df.plot.box,# plotter...column="age",by="gender",figsize=(4,3))# ...forwarded kwargsteepots/by=gender+column=age+viz=box+ext=.pdfteepots/by=gender+column=age+viz=box+ext=.pngExample 2Example withseabornshowing use ofteeplot_callbackkwarg to allow for plot tweaks before saving.# adapted from https://seaborn.pydata.org/examples/horizontal_boxplot.htmlfrommatplotlibimportpyplotaspltimportseabornassnsfromteeplotimportteeplotastpsaveit,ax=tp.tee(# create a callback object to finalize plotsns.boxplot,# plotter...sns.load_dataset("planets"),# ...forwarded arg & kwargsx="distance",y="method",hue="method",palette="vlag",whis=[0,100],width=.6,# ... and then teeplot optionsteeplot_callback=True,teeplot_postprocess="teed.set_xscale('log')")ax.xaxis.grid(True)# now some tweaksax.set(ylabel="")sns.despine()plt.gcf().set_size_inches(10,4)saveit()# dispatch output callbackteepots/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=.pdf
teepots/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=.pngExample 3Example with matplotlib, also showing use ofteeplot_callbackkwarg .# adapted from https://matplotlib.org/stable/tutorials/pyplot.htmlfrommatplotlibimportpyplotaspltimportnumpyasnp;fromteeplotimportteeplotastpdata={'a':np.arange(50),'c':np.random.randint(0,50,50),'d':np.random.randn(50)}data['b'],data['d']=data['a']+10*np.random.randn(50),np.abs(data['d'])*100saveit,__=tp.tee(# create a callback object to finalize plotplt.scatter,# plotter...data=data,x='a',y='b',c='c',s='d',# ...forwarded kwargsteeplot_callback=True)# teeplot optionsplt.xlabel('entry a')# now some tweaksplt.ylabel('entry b')plt.gcf().set_size_inches(5,3)saveit()# dispatch output callbackteepots/c=c+s=d+viz=scatter+x=a+y=b+ext=.pdfteepots/c=c+s=d+viz=scatter+x=a+y=b+ext=.pngExample 4Example withseabornFacetGriddemonstrating use ofexec’edteeplot_postprocessthat adds amap_dataframestep over theteedresult value and also results in additional semantic information being added to plot filenames (under the “post=” key).# adapted from https://seaborn.pydata.org/generated/seaborn.FacetGrid.html#seaborn.FacetGridimportseabornassnsfromteeplotimportteeplotastptp.tee(sns.FacetGrid,# plotter...sns.load_dataset("tips"),# ...forwarded args & kwwargscol="time",hue="sex",aspect=1.5,teeplot_postprocess="teed.map_dataframe(sns.scatterplot, x='total_bill', y='tip')")teepots/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=.pdf
teepots/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=.pngExample 5Demonstration of teeplot use with a custom function.
Note the function name automatically used as “viz=” key in output filenames.# adapted from https://seaborn.pydata.org/examples/pairgrid_dotplot.htmlimportseabornassns;fromteeplotimportteeplotastpdf=sns.load_dataset("car_crashes")defdot_plot(data,x_vars,y_vars):# custom plotterg=sns.PairGrid(data.sort_values("total",ascending=False),x_vars=x_vars,y_vars=y_vars,height=5,aspect=0.66)g.map(sns.stripplot,size=10,orient="h",jitter=False,palette="flare_r",linewidth=1,edgecolor="w")foraxing.axes.flat:ax.xaxis.grid(False)ax.yaxis.grid(True)tp.tee(dot_plot,# plotter, then forwarded args/kwargsdf[df["abbrev"].str.contains("A")],x_vars=df.columns[:-3],y_vars=["abbrev"],teeplot_outinclude=["x_vars","y_vars"],teeplot_save={".eps",".png"})teeplots/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=.eps
teeplots/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=.pngAPIteeplot.tee()Executes a plotting function and saves the resulting plot to specified formats using a descriptive filename automatically generated from plotting function arguments.ParameterDescriptionplotterThe plotting function to be executed.Required.Additional args & kwargsForwarded to the plotting function and used to build the output filename.teeplot_callbackIf True, returns a tuple with a callback to dispatch plot save instead of immediately saving the plot after running the plotter. Default is False.teeplot_dpiResolution for rasterized components of saved plots, default is publication-quality 300 dpi.teeplot_oncollisionStrategy for handling filename collisions: “error”, “fix”, “ignore”, or “warn”, default “warn”; inferred from environment if not specified.teeplot_outattrsDict with additional key-value attributes to include in the output filename.teeplot_outdirBase directory for saving plots, default “teeplots”.teeplot_outincludeAttribute keys to always include, if present, in the output filename.teeplot_outexcludeAttribute keys to always exclude, if present, from the output filename.teeplot_postprocessActions to perform after plotting but before saving. Can be a string of code toexecor a callable function. If a string, it’s executed with access topltandsns(if installed), and the plotter return value asteed.teeplot_saveFile formats to save the plots in. Defaults to global settings ifTrue, all output suppressed ifFalse. Default global setting is{" .png", ".pdf"}. Supported: “.eps”, “.png”, “.pdf”, “.ps”, “.svg”.teeplot_showDictates whetherplt.show()should be called after plot is saved. If True, the plot is displayed usingplt.show(). Default behavior is to display if an interactive environment is detected (e.g., a notebook).teeplot_subdirOptionally, subdirectory within the main output directory for plot organization.teeplot_transparentOption to save the plot with a transparent background, default True.teeplot_verboseToggles printing of saved filenames, default True.Return Value: returned result from plotter call ifteeplot_callbackisFalse, otherwise tuple of save-plot callback and result from plotter call.Module-Level Configurationteeplot.draftmode: A boolean indicating whether to suppress output to all file formats.teeplot.oncollision: Default strategy for handling filename collisions, with options like ‘error’, ‘fix’, ‘ignore’, or ‘warn’.teeplot.save: A dictionary mapping file formats (e.g., “.png”) to default save behavior asTrue(always output),False(never output), orNone(defer to call kwargs).Environment VariablesTEEPLOT_ONCOLLISION: Configures the default collision handling strategy. Seeteeplot_oncollisionkwargTEEPLOT_DRAFTMODE: If set, enables draft mode globally.TEEPLOT_<FORMAT>: Boolean flags that determine default behavior for each format (e.g.,EPS,PNG,PDF,PS,SVG); “defer” defers to call kwargs.CI, etc.: If a continuous integration environment is detected, defaultteeplot_savebehavior will output only.pdffiles, instead of.pdfand.pngfiles. This can be overridden withTEEPLOT_<FORMAT>.CreditsOutput filenames are constructed using thekeynamepackage.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.