sc_plotting
Extensions to Matplotlib, including 3D plotting and plot customization.
Highlights
sc.plot3d(): easy way to render 3D plotssc.boxoff(): turn off top and right parts of the axes boxsc.commaticks(): convert labels from “10000” and “1e6” to “10,000” and “1,000,0000”sc.SIticks(): convert labels from “10000” and “1e6” to “10k” and “1m”sc.maximize(): make the figure fill the whole screensc.savemovie(): save a sequence of figures as an MP4 or other moviesc.fonts(): list available fonts or add new ones
Classes
| Name | Description |
|---|---|
| ScirisDateFormatter | An adaptation of Matplotlib’s ConciseDateFormatter with a slightly different |
| animation | A class for storing and saving a Matplotlib animation. |
ScirisDateFormatter
sc_plotting.ScirisDateFormatter(
locator,
formats=None,
zero_formats=None,
show_offset=False,
show_year=True,
**kwargs,
)An adaptation of Matplotlib’s ConciseDateFormatter with a slightly different approach to formatting dates. Specifically:
- Years are shown below dates, rather than on the RHS
- The day and month are always shown.
- The cursor shows only the date, not the time
This formatter is not intended to be called directly – use sc.dateformatter() instead. It is also optimized for plotting dates, rather than times – for those, ConciseDateFormatter is better.
See sc.dateformatter() for explanation of arguments.
New in version 1.3.0.
Methods
| Name | Description |
|---|---|
| format_data_short | Show year-month-day, not with hours and seconds |
| format_ticks | Append the year to the tick label for the first label, or if the year changes. |
format_data_short
sc_plotting.ScirisDateFormatter.format_data_short(value)Show year-month-day, not with hours and seconds
format_ticks
sc_plotting.ScirisDateFormatter.format_ticks(
values,
min_year=1700,
max_year=2300,
)Append the year to the tick label for the first label, or if the year changes. This avoids the need to use offset_text, which is difficult to control.
animation
sc_plotting.animation(
fig=None,
filename=None,
dpi=200,
fps=10,
imageformat='png',
basename='animation',
nametemplate=None,
imagefolder=None,
anim_args=None,
save_args=None,
frames=None,
tidy=True,
verbose=True,
**kwargs,
)A class for storing and saving a Matplotlib animation.
See also sc.savemovie(), which works directly with Matplotlib artists rather than an entire figure. Depending on your use case, one is likely easier to use than the other. Use sc.animation() if you want to animate a complex figure including non-artist objects (e.g., titles and legends); use sc.savemovie() if you just want to animate a set of artists (e.g., lines).
This class works by saving snapshots of the figure to disk as image files, then reloading them either via ffmpeg or as a Matplotlib animation. While (slightly) slower than working with artists directly, it means that anything that can be rendered to a figure can be animated.
Note: the terms “animation” and “movie” are used interchangeably here.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| fig | fig |
the Matplotlib figure to animate (if none, use current) | None |
| filename | str | the name of the output animation (default: animation.mp4) | None |
| dpi | int | the resolution to save the animation at | 200 |
| fps | int | frames per second for the animation | 10 |
| imageformat | str | file type for temporary image files, e.g. ‘jpg’ | 'png' |
| basename | str | name for temporary image files, e.g. ‘myanimation’ | 'animation' |
| nametemplate | str | as an alternative to imageformat and basename, specify the full name template, e.g. ‘myanimation%004d.jpg’ | None |
| imagefolder | str | location to store temporary image files; default current folder, or use ‘tempfile’ to create a temporary folder | None |
| anim_args | dict | passed to matplotlib.animation.ArtistAnimation or ffmpeg.input() |
None |
| save_args | dict | passed to animation.save() or ffmpeg.run() |
None |
| tidy | bool | whether to delete temporary files | True |
| verbose | bool | whether to print progress | True |
| kwargs | dict | also passed to animation.save() |
{} |
Example:
anim = sc.animation()
plt.figure()
repeats = 21
colors = sc.vectocolor(repeats, cmap='turbo')
for i in range(repeats):
scale = 1/np.sqrt(i+1)
x = scale*np.random.randn(10)
y = scale*np.random.randn(10)
label = str(i) if not(i%5) else None
plt.scatter(x, y, c=[colors[i]], label=label)
plt.title(f'Scale = 1/√{i}')
plt.legend()
sc.boxoff('all')
anim.addframe()
anim.save('dots.mp4')- New in version 1.3.3.
- New in version 2.0.0:
ffmpegoption.
Methods
| Name | Description |
|---|---|
| addframe | Add a frame to the animation – typically a figure object, but can also be an artist or list of artists |
| initialize | Handle additional initialization of variables |
| loadframes | Load saved images as artists |
| rmfiles | Remove temporary image files |
| save | Save the animation – arguments the same as sc.animation() and sc.savemovie(), and are described there |
addframe
sc_plotting.animation.addframe(fig=None, *args, **kwargs)Add a frame to the animation – typically a figure object, but can also be an artist or list of artists
initialize
sc_plotting.animation.initialize()Handle additional initialization of variables
loadframes
sc_plotting.animation.loadframes()Load saved images as artists
rmfiles
sc_plotting.animation.rmfiles()Remove temporary image files
save
sc_plotting.animation.save(
filename=None,
fps=None,
dpi=None,
engine='ffmpeg',
anim_args=None,
save_args=None,
frames=None,
tidy=None,
verbose=True,
**kwargs,
)Save the animation – arguments the same as sc.animation() and sc.savemovie(), and are described there
Functions
| Name | Description |
|---|---|
| SIticks | Apply SI tick formatting to one axis of a figure (e.g., 34k instead of 34000) |
| ax3d | Create a 3D axis to plot in. |
| bar3d | Plot 2D data as 3D bars |
| boxoff | Removes the top and right borders (“spines”) of a plot. |
| commaticks | Use commas in formatting the y axis of a figure (e.g., 34,000 instead of 34000). |
| dateformatter | Format the x-axis to use a given date formatter. |
| datenumformatter | Format a numeric x-axis to use dates. |
| emptyfig | The emptiest figure possible |
| fig3d | Shortcut for creating a figure with 3D axes. |
| figlayout | Alias to both fig.set_layout_engine() |
| fonts | List available fonts, or add new ones. Alias to Matplotlib’s font manager. |
| getrowscols | Get the number of rows and columns needed to plot N figures. |
| loadfig | Load a plot from a file and reanimate it. |
| maximize | Maximize the current (or supplied) figure. Note: not guaranteed to work for |
| movelegend | Move the legend from one axes to another, preserving properties. |
| orderlegend | Create a legend with a specified order, or change the order of an existing legend. |
| plot3d | Plot 3D data as a line |
| savefig | Save a figure, including metadata |
| savefigs | Save the requested plots to disk. |
| savemovie | Save a set of Matplotlib artists as a movie. |
| scatter3d | Plot 3D data as a scatter |
| separatelegend | Allows the legend of a figure to be rendered in a separate window instead |
| setaxislim | A small script to determine how the y limits should be set. Looks |
| setxlim | Alias for sc.setaxislim(which='x') |
| setylim | Alias for sc.setaxislim(which='y'). |
| stackedbar | Create a stacked bar chart. |
| surf3d | Plot 2D or 3D data as a 3D surface |
SIticks
sc_plotting.SIticks(ax=None, axis='y', fixed=False)Apply SI tick formatting to one axis of a figure (e.g., 34k instead of 34000)
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ax | any | axes to modify; if None, use current; else can be a single axes object, a figure, or a list of axes | None |
| axis | str | which axes to change (default ‘y’) | 'y' |
Example:
data = np.random.rand(10)*1e4
plt.plot(data)
sc.SIticks()ax3d
sc_plotting.ax3d(
nrows=None,
ncols=None,
index=None,
fig=None,
ax=None,
returnfig=False,
elev=None,
azim=None,
figkwargs=None,
**kwargs,
)Create a 3D axis to plot in.
Usually not invoked directly; kwargs are passed to fig.add_subplot()
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| nrows | int | number of rows of axes in plot | None |
| ncols | int | number of columns of axes in plot | None |
| index | int | index of current plot | None |
| fig | Figure |
if provided, use existing figure | None |
| ax | Axes |
if provided, validate and use these axes | None |
| returnfig | bool | whether to return the figure (else just the axes) | False |
| elev | float | the elevation of the 3D viewpoint | None |
| azim | float | the azimuth of the 3D viewpoint | None |
| figkwargs | dict | passed to plt.figure() |
None |
| kwargs | dict | passed to plt.axes() |
{} |
- New in version 3.0.0: nrows, ncols, and index arguments first
- New in version 3.1.0: improved validation; ‘silent’ and ‘axkwargs’ argument removed
bar3d
sc_plotting.bar3d(
x=None,
y=None,
z=None,
c='z',
dx=0.8,
dy=0.8,
dz=None,
fig=True,
ax=None,
returnfig=False,
figkwargs=None,
axkwargs=None,
**kwargs,
)Plot 2D data as 3D bars
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | arr |
1D or 2D array of x coordinates (or z-coordinate data if 2D and z is None) |
None |
| y | arr |
1D or 2D array of y coordinates (optional) | None |
| z | arr |
2D array of z coordinates; interpreted as the heights of the bars unless dz is also provided |
None |
| c | arr |
color data; defaults to match z | 'z' |
| dx | float / arr |
width of the bars | 0.8 |
| dy | float / arr |
depth of the bars | 0.8 |
| dz | float / arr |
height of the bars, in which case z is interpreted as the base of the bars |
None |
| fig | fig |
an existing figure to draw the plot in (or set to True to create a new figure) | True |
| ax | axes |
an existing axes to draw the plot in | None |
| returnfig | bool | whether to return the figure, or just the axes | False |
| colorbar | bool | whether to plot a colorbar (true by default unless color data is provided) | required |
| figkwargs | dict | passed to plt.figure() |
None |
| axkwargs | dict | passed to plt.axes() |
None |
| kwargs | dict | passed to ax.bar3d() |
{} |
Examples:
# Simple example
data = np.random.rand(5,4)
sc.bar3d(data)
# Use non-default axes and colors (note: this one is pretty!)
nx = 5
ny = 6
x = 10*np.arange(nx)
y = np.arange(ny) + 10
z = -np.random.rand(ny,nx)
dz = -2*z
c = z**2
sc.bar3d(x=x, y=y, z=z, dx=0.5, dy=0.5, dz=dz, c=c, cmap='orangeblue')New in 3.1.0: updated arguments from “data” to x, y, z, c; removed “plotkwargs” argument; “fig” defaults to True
boxoff
sc_plotting.boxoff(ax=None, which=None, removeticks=True)Removes the top and right borders (“spines”) of a plot.
Also optionally removes the tick marks, and flips the remaining ones outside. Can be used as an alias to plt.axis('off') if which='all'.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ax | Axes |
the axes to remove the spines from (if None, use current) | None |
| which | str / list | a list or comma-separated string of spines: ‘top’, ‘bottom’, ‘left’, ‘right’, or ‘all’ (default top & right) | None |
| removeticks | bool | whether to also remove the ticks from these spines | True |
| flipticks | bool | whether to flip remaining ticks out | required |
Examples:
plt.figure()
plt.plot([2,5,3])
sc.boxoff()
fig, ax = plt.subplots()
plt.plot([1,4,1,4])
sc.boxoff(ax=ax, which='all')
fig = plt.figure()
plt.scatter(np.arange(100), np.random.rand(100))
sc.boxoff('top, bottom')New in version 1.3.3: ability to turn off multiple spines; removed “flipticks” arguments
commaticks
sc_plotting.commaticks(ax=None, axis='y', precision=2, cursor_precision=0)Use commas in formatting the y axis of a figure (e.g., 34,000 instead of 34000).
To use something other than a comma, set the default separator via e.g. sc.options(sep='.').
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ax | any | axes to modify; if None, use current; else can be a single axes object, a figure, or a list of axes | None |
| axis | str / list | which axis to change (default ‘y’; can accept a list) | 'y' |
| precision | int | shift how many decimal places to show for small numbers (+ve = more, -ve = fewer) | 2 |
| cursor_precision | int | ditto, for cursor | 0 |
Example:
data = np.random.rand(10)*1e4
plt.plot(data)
sc.commaticks()See http://stackoverflow.com/questions/25973581/how-to-format-axis-number-format-to-thousands-with-a-comma-in-matplotlib
- New in version 1.3.0: ability to use non-comma thousands separator
- New in version 1.3.1: added “precision” argument
- New in version 2.0.0: ability to set x and y axes simultaneously
dateformatter
sc_plotting.dateformatter(
ax=None,
style='sciris',
dateformat=None,
start=None,
end=None,
rotation=None,
locator=None,
axis='x',
**kwargs,
)Format the x-axis to use a given date formatter.
By default, this will apply the Sciris date formatter to the current x-axis. This formatter is a combination of Matplotlib’s Concise date formatter, and Plotly’s date formatter.
See also sc.datenumformatter() to convert a numeric axis to date labels.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ax (axes) | if supplied, use these axes instead of the current one | required | |
| style (str) | the style to use if the axis already uses dates; options are “sciris”, “auto”, “concise”, or a Formatter object | required | |
| dateformat (str) | the date format (default '%Y-%b-%d'; not needed if x-axis already uses dates) |
required | |
| start (str/int) | if supplied, the lower limit of the axis | required | |
| end (str/int) | if supplied, the upper limit of the axis | required | |
| rotation (float) | rotation of the labels, in degrees | required | |
| locator (Locator) | if supplied, use this instead of the default AutoDateLocator locator |
required | |
| axis (str) | which axis to apply to the formatter to (default ‘x’) | required | |
| kwargs (dict) | passed to the date formatter (e.g., ScirisDateFormatter) |
required |
Examples:
# Reformat date data
plt.figure()
x = sc.daterange('2021-04-04', '2022-05-05', asdate=True)
y = sc.smooth(np.random.rand(len(x)))
plt.plot(x, y)
sc.dateformatter()
# Configure with Matplotlib's Concise formatter
fig,ax = plt.subplots()
plt.plot(sc.date(np.arange(365), start_date='2022-01-01'), np.random.randn(365))
sc.dateformatter(ax=ax, style='concise')- New in version 1.2.0.
- New in version 1.2.2: “rotation” argument; renamed “start_day” to “start_date”
- New in version 1.3.0: refactored to use built-in Matplotlib date formatting
- New in version 1.3.2: “axis” argument
- New in version 1.3.3: split
sc.dateformatter()fromsc.datenumformatter()
datenumformatter
sc_plotting.datenumformatter(
ax=None,
start_date=None,
dateformat=None,
interval=None,
start=None,
end=None,
rotation=None,
)Format a numeric x-axis to use dates.
Note: in most cases, sc.dateformatter() should be used instead; use this function only if you want to explicitly specify start and end values, i.e., specify the date data rather than simply plot it.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ax (axes) | if supplied, use these axes instead of the current one | required | |
| start_date (str/date) | the start day, either as a string or date object (not needed if x-axis already uses dates) | required | |
| dateformat (str) | the date format (default '%Y-%b-%d'; not needed if x-axis already uses dates) |
required | |
| interval (int) | if supplied, the interval between ticks (not needed if x-axis already uses dates) | required | |
| start (str/int) | if supplied, the lower limit of the axis | required | |
| end (str/int) | if supplied, the upper limit of the axis | required | |
| rotation (float) | rotation of the labels, in degrees | required |
Examples:
# Automatically configure a non-date axis with default options
plt.plot(np.arange(365), np.random.rand(365))
sc.datenumformatter(start_date='2021-01-01')
# Manually configure
fig,ax = plt.subplots()
ax.plot(np.arange(60), np.random.random(60))
formatter = sc.datenumformatter(start_date='2020-04-04', interval=7, start='2020-05-01', end=50, dateformat='%m-%d', ax=ax)- New in version 1.2.0.
- New in version 1.2.2: “rotation” argument; renamed “start_day” to “start_date”
- New in version 1.3.3: renamed from
sc.dateformatter()tosc.datenumformatter()
emptyfig
sc_plotting.emptyfig(*args, **kwargs)The emptiest figure possible
fig3d
sc_plotting.fig3d(
num=None,
nrows=1,
ncols=1,
index=1,
returnax=False,
figkwargs=None,
axkwargs=None,
**kwargs,
)Shortcut for creating a figure with 3D axes.
Usually not invoked directly; kwargs are passed to plt.figure()
figlayout
sc_plotting.figlayout(fig=None, tight=True, keep=None, **kwargs)Alias to both fig.set_layout_engine() and fig.subplots_adjust().
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| fig | Figure |
the figure (by default, use current) | None |
| tight | bool | passed to fig.set_layout_engine(); default True |
True |
| keep | bool | if True, then leave tight layout on; else, turn it back off to allow additional layout updates (which requires a render, so can be slow) | None |
| kwargs | dict | passed to fig.subplots_adjust() |
{} |
Example:
fig,axs = sc.get_rows_cols(37, make=True, tight=False) # Create 7x6 subplots, squished together
sc.figlayout(bottom=0.3)- New in version 1.2.0.
- New in version 3.1.1:
keepdefaults toTrueto avoid the need to refresh
fonts
sc_plotting.fonts(
add=None,
use=False,
output='name',
dryrun=False,
rebuild=False,
verbose=False,
die=False,
**kwargs,
)List available fonts, or add new ones. Alias to Matplotlib’s font manager.
Note: if the font is not available after adding it, set rebuild=True. However, note that this can be very slow.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| add | str / list | path of the fonts or folders to add; if none, list available fonts | None |
| use | bool | set the last-added font as the default font | False |
| output | str | what to display the listed fonts as: options are ‘name’ (list of names, default), ‘path’ (dict of name:path), or ‘font’ (dict of name:font object) | 'name' |
| dryrun | bool | list fonts to be added rather than adding them | False |
| rebuild | bool | whether to rebuild Matplotlib’s font cache (slow) | False |
| verbose | bool | print out information on errors | False |
| die | bool | whether to raise an exception if fonts can’t be added | False |
| kwargs | dict | passed to matplotlib.font_manager.findSystemFonts() |
{} |
Examples:
sc.fonts() # List available font names
sc.fonts(fullfont=True) # List available font objects
sc.fonts('myfont.ttf', use=True) # Add this font and immediately set to default
sc.fonts(['/folder1', '/folder2']) # Add all fonts in both folders
sc.fonts(rebuild=True) # Run this if added fonts aren't appearinggetrowscols
sc_plotting.getrowscols(
n,
nrows=None,
ncols=None,
ratio=1,
make=False,
tight=True,
remove_extra=True,
**kwargs,
)Get the number of rows and columns needed to plot N figures.
If you have 37 plots, then how many rows and columns of axes do you know? This function convert a number (i.e. of plots) to a number of required rows and columns. If nrows or ncols is provided, the other will be calculated. Ties are broken in favor of more rows (i.e. 7x6 is preferred to 6x7). It can also generate the plots, if make=True.
Note: sc.getrowscols() and sc.get_rows_cols() are aliases.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| n | int | the number (of plots) to accommodate | required |
| nrows | int | if supplied, keep this fixed and calculate the columns | None |
| ncols | int | if supplied, keep this fixed and calculate the rows | None |
| ratio | float | sets the number of rows relative to the number of columns (i.e. for 100 plots, 1 will give 10x10, 4 will give 20x5, etc.). | 1 |
| make | bool | if True, generate subplots | False |
| tight | bool | if True and make is True, then apply tight layout | True |
| remove_extra | bool | if True and make is True, then remove extra subplots | True |
| kwargs | dict | passed to plt.subplots() | {} |
Returns
| Name | Type | Description |
|---|---|---|
| A tuple of ints for the number of rows and the number of columns (which, of course, you can reverse) |
Examples:
nrows,ncols = sc.get_rows_cols(36) # Returns 6,6
nrows,ncols = sc.get_rows_cols(37) # Returns 7,6
nrows,ncols = sc.get_rows_cols(100, ratio=2) # Returns 15,7
nrows,ncols = sc.get_rows_cols(100, ratio=0.5) # Returns 8,13 since rows are prioritized
fig,axs = sc.getrowscols(37, make=True) # Create 7x6 subplots, using the alias- New in version 1.0.0.
- New in version 1.2.0: “make”, “tight”, and “remove_extra” arguments
- New in version 1.3.0: alias without underscores
- New in version 3.2.2: extra axes deleted rather than set to invisible
loadfig
sc_plotting.loadfig(filename=None)Load a plot from a file and reanimate it.
Example usage:
import matplotlib.pyplot as plt
import sciris as sc
fig = plt.figure(); plt.plot(np.random.rand(10))
sc.savefigs(fig, filetype='fig', filename='example.fig')Later:
example = sc.loadfig('example.fig')maximize
sc_plotting.maximize(fig=None, die=False)Maximize the current (or supplied) figure. Note: not guaranteed to work for all Matplotlib backends (e.g., agg).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| fig | Figure |
the figure object; if not supplied, use the current active figure | None |
| die | bool | whether to propagate an exception if encountered (default no) | False |
Example:
plt.plot([2,3,5])
sc.maximize()New in version 1.0.0.
movelegend
sc_plotting.movelegend(ax1, ax2=None, invisible=True, **kwargs)Move the legend from one axes to another, preserving properties.
Note 1: does not require the first legend to actually exist, just that handles exist (e.g. by plotting with the “label” argument); see example below.
Note 2: see seaborn.move_legend() for a similar function.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ax1 | plt.Axes |
the axes to move the legend from | required |
| ax2 | plt.Axes |
the axes to move the legend to (if None, use current axes) | None |
| invisible | bool | if True, set the axis to be invisible (just showing the legend) if no artists are in the destination axes | True |
| kwargs | dict | passed to plt.legend() |
{} |
Example:
import numpy as np
import sciris as sc
fig, axs = sc.getrowscols(3, make=True)
for i,ax in enumerate(fig.axes):
for j in range(4):
ax.plot(np.random.rand(50)*(1+j), 'o', label=f'Scale = {j}')
ax4 = fig.add_subplot(2,2,4)
sc.movelegend(ax, ax4) # Can be any of the axes since they have the same legend- New in version 3.2.2.
orderlegend
sc_plotting.orderlegend(
order=None,
ax=None,
handles=None,
labels=None,
reverse=None,
**kwargs,
)Create a legend with a specified order, or change the order of an existing legend. Can either specify an order, or use the reverse argument to simply reverse the order. Note: you do not need to create the legend before calling this function; if you do, you will need to pass any additional keyword arguments to this function since it will override existing settings.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| order | list or array | the new order of the legend, as from e.g. np.argsort() | None |
| ax | axes |
the axes object; if omitted, defaults to current axes | None |
| handles | list | the legend handles; can be used instead of ax | None |
| labels | list | the legend labels; can be used instead of ax | None |
| reverse | bool | if supplied, simply reverse the legend order | None |
| kwargs | dict | passed to ax.legend() | {} |
Examples:
plt.plot([1,4,3], label='A')
plt.plot([5,7,8], label='B')
plt.plot([2,5,2], label='C')
sc.orderlegend(reverse=True) # Legend order C, B, A
sc.orderlegend([1,0,2], frameon=False) # Legend order B, A, C with no frame
plt.legend() # Restore original legend order A, B, Cplot3d
sc_plotting.plot3d(
x,
y,
z,
c='index',
fig=True,
ax=None,
returnfig=False,
figkwargs=None,
axkwargs=None,
**kwargs,
)Plot 3D data as a line
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | arr |
x coordinate data | required |
| y | arr |
y coordinate data | required |
| z | arr |
z coordinate data | required |
| c | str / tuple | color, can be an array or any of the types accepted by plt.plot(); if ‘index’ (default), color by index |
'index' |
| fig | fig |
an existing figure to draw the plot in (or set to True to create a new figure) | True |
| ax | axes |
an existing axes to draw the plot in | None |
| returnfig | bool | whether to return the figure, or just the axes | False |
| figkwargs | dict | plt.figure() |
None |
| axkwargs | dict | plt.axes() |
None |
| kwargs | dict | passed to plt.plot() |
{} |
Returns
| Name | Type | Description |
|---|---|---|
ax if returnfig=False; (fig,ax) if returnfig=True |
Examples:
x,y,z = np.random.rand(3,10)
sc.plot3d(x, y, z)
fig = plt.figure()
n = 100
x = np.array(sorted(np.random.rand(n)))
y = x + np.random.randn(n)
z = np.random.randn(n)
c = np.arange(n)
sc.plot3d(x, y, z, c=c, fig=fig)New in version 3.1.0: Allow multi-colored line; removed “plotkwargs” argument; “fig” defaults to True
savefig
sc_plotting.savefig(
filename,
fig=None,
dpi=None,
comments=None,
pipfreeze=False,
relframe=0,
folder=None,
makedirs=True,
die=True,
verbose=True,
**kwargs,
)Save a figure, including metadata
Wrapper for Matplotlib’s plt.savefig() function which automatically stores metadata in the figure. By default, it saves (git) information from the calling function. Additional comments can be added to the saved file as well. These can be retrieved via sc.loadmetadata().
Metadata can be stored and retrieved for PNG or SVG. Metadata can be stored for PDF, but cannot be automatically retrieved.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| filename (str/Path) | name of the file to save to | required | |
| fig (Figure) | the figure to save (if None, use current) | required | |
| dpi (int) | resolution of the figure to save (default 200 or current default, whichever is higher) | required | |
| comments (str) | additional metadata to save to the figure | required | |
| pipfreeze (bool) | whether to store the contents of pip freeze in the metadata |
required | |
| relframe (int) | which calling file to try to store information from (default 0, the file calling sc.savefig()) |
required | |
| folder (str/Path) | optional folder to save to (can also be provided as part of the filename) | required | |
| makedirs (bool) | whether to create folders if they don’t already exist | required | |
| die (bool) | whether to raise an exception if metadata can’t be saved | required | |
| verbose (bool) | if die is False, print a warning if metadata can’t be saved | required | |
| kwargs (dict) | passed to fig.save() |
required |
Examples:
plt.plot([1,3,7])
sc.savefig('example1.png')
print(sc.loadmetadata('example1.png'))
sc.savefig('example2.png', comments='My figure', freeze=True)
sc.pp(sc.loadmetadata('example2.png'))- New in version 1.3.3.
- New in version 3.0.0: “freeze” renamed “pipfreeze”; “frame” replaced with “relframe”; replaced metadata with
sc.metadata()
savefigs
sc_plotting.savefigs(
figs=None,
filetype=None,
filename=None,
folder=None,
savefigargs=None,
aslist=False,
verbose=False,
**kwargs,
)Save the requested plots to disk.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| figs (list) | the figure objects to save | required | |
| filetype (str) | the file type; can be ‘fig’, ‘singlepdf’ (default), or anything supported by savefig() | required | |
| filename (str) | the file to save to (only uses path if multiple files) | required | |
| folder (str) | the folder to save the file(s) in | required | |
| savefigargs (dict) | arguments passed to savefig() | required | |
| aslist (bool) | whether or not return a list even for a single file | required | |
| varbose (bool) | whether to print progress | required |
Examples:
import matplotlib.pyplot as plt
import sciris as sc
fig1 = plt.figure(); plt.plot(np.random.rand(10))
fig2 = plt.figure(); plt.plot(np.random.rand(10))
sc.savefigs([fig1, fig2]) # Save everything to one PDF file
sc.savefigs(fig2, 'png', filename='myfig.png', savefigargs={'dpi':200})
sc.savefigs([fig1, fig2], filepath='/home/me', filetype='svg')
sc.savefigs(fig1, position=[0.3,0.3,0.5,0.5])If saved as ‘fig’, then can load and display the plot using sc.loadfig().
Version: 2018aug26
savemovie
sc_plotting.savemovie(
frames,
filename=None,
fps=None,
quality=None,
dpi=None,
writer=None,
bitrate=None,
interval=None,
repeat=False,
repeat_delay=None,
blit=False,
verbose=True,
**kwargs,
)Save a set of Matplotlib artists as a movie.
Note: in most cases, it is preferable to use sc.animation().
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| frames | list | The list of frames to animate | required |
| filename | str | The name (or full path) of the file; expected to end with mp4 or gif (default movie.mp4) | None |
| fps | int | The number of frames per second (default 10) | None |
| quality | string | The quality of the movie, in terms of dpi (default “high” = 300 dpi) | None |
| dpi | int | Instead of using quality, set an exact dpi | None |
| writer | str or object | Specify the writer to be passed to animation.save() (default “ffmpeg”) |
None |
| bitrate | int | The bitrate. Note, may be ignored; best to specify in a writer and to pass in the writer as an argument | None |
| interval | int | The interval between frames; alternative to using fps | None |
| repeat | bool | Whether or not to loop the animation (default False) | False |
| repeat_delay | bool | Delay between repeats, if repeat=True (default None) | None |
| blit | bool | Whether or not to “blit” the frames (default False, since otherwise does not detect changes ) | False |
| verbose | bool | Whether to print statistics on finishing. | True |
| kwargs | dict | Passed to animation.save() |
{} |
Returns
| Name | Type | Description |
|---|---|---|
| A Matplotlib animation object |
Examples:
import matplotlib.pyplot as plt
import sciris as sc
# Simple example (takes ~5 s)
plt.figure()
frames = [pl.plot(np.cumsum(np.random.randn(100))) for i in range(20)] # Create frames
sc.savemovie(frames, 'dancing_lines.gif') # Save movie as medium-quality gif
# Complicated example (takes ~15 s)
plt.figure()
nframes = 100 # Set the number of frames
ndots = 100 # Set the number of dots
axislim = 5*pl.sqrt(nframes) # Pick axis limits
dots = plt.zeros((ndots, 2)) # Initialize the dots
frames = [] # Initialize the frames
old_dots = sc.dcp(dots) # Copy the dots we just made
fig = plt.figure(figsize=(10,8)) # Create a new figure
for i in range(nframes): # Loop over the frames
dots += np.random.randn(ndots, 2) # Move the dots randomly
color = plt.norm(dots, axis=1) # Set the dot color
old = plt.array(old_dots) # Turn into an array
plot1 = plt.scatter(old[:,0], old[:,1], c='k') # Plot old dots in black
plot2 = plt.scatter(dots[:,0], dots[:,1], c=color) # Note: Frames will be separate in the animation
plt.xlim((-axislim, axislim)) # Set x-axis limits
plt.ylim((-axislim, axislim)) # Set y-axis limits
kwargs = {'transform':pl.gca().transAxes, 'horizontalalignment':'center'} # Set the "title" properties
title = plt.text(0.5, 1.05, f'Iteration {i+1}/{nframes}', **kwargs) # Unfortunately plt.title() can't be dynamically updated
plt.xlabel('Latitude') # But static labels are fine
plt.ylabel('Longitude') # Ditto
frames.append((plot1, plot2, title)) # Store updated artists
old_dots = plt.vstack([old_dots, dots]) # Store the new dots as old dots
sc.savemovie(frames, 'fleeing_dots.mp4', fps=20, quality='high') # Save movie as a high-quality mp4Version: 2019aug21
scatter3d
sc_plotting.scatter3d(
x=None,
y=None,
z=None,
c='z',
fig=True,
ax=None,
returnfig=False,
figkwargs=None,
axkwargs=None,
**kwargs,
)Plot 3D data as a scatter
Typically, x, y, and z, are all vectors. However, if a single 2D array is provided, then this will be treated as z values and x and y will be inferred on a grid (or they can be provided explicitly).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | arr |
1D or 2D x coordinate data (or z-coordinate data if 2D and z is None) |
None |
| y | arr |
1D or 2D y coordinate data | None |
| z | arr |
1D or 2D z coordinate data | None |
| c | arr |
color data; defaults to match z; to use default colors, explicitly pass c=None; to use index, use c=‘index’ |
'z' |
| fig | fig |
an existing figure to draw the plot in (or set to True to create a new figure) | True |
| ax | axes |
an existing axes to draw the plot in | None |
| returnfig | bool | whether to return the figure, or just the axes | False |
| figkwargs | dict | passed to plt.figure() |
None |
| axkwargs | dict | passed to plt.axes() |
None |
| kwargs | dict | passed to plt.scatter() |
{} |
Examples:
# Implicit coordinates, color by height (z-value)
data = np.random.randn(10, 10)
sc.scatter3d(data)
# Explicit coordinates, color by index (i.e. ordering)
x,y,z = np.random.rand(3,50)
sc.scatter3d(x, y, z, c='index')- New in version 3.0.0: Allow 2D input
- New in version 3.1.0: Allow “index” color argument; removed “plotkwargs” argument; “fig” defaults to True
separatelegend
sc_plotting.separatelegend(
ax=None,
handles=None,
labels=None,
reverse=False,
figsettings=None,
legendsettings=None,
)Allows the legend of a figure to be rendered in a separate window instead
setaxislim
sc_plotting.setaxislim(which=None, ax=None, data=None)A small script to determine how the y limits should be set. Looks at all data (a list of arrays) and computes the lower limit to use, e.g.:
sc.setaxislim([np.array([-3,4]), np.array([6,4,6])], ax)will keep Matplotlib’s lower limit, since at least one data value is below 0.
Note, if you just want to set the lower limit, you can do that with this function via:
sc.setaxislim()setxlim
sc_plotting.setxlim(data=None, ax=None)Alias for sc.setaxislim(which='x')
setylim
sc_plotting.setylim(data=None, ax=None)Alias for sc.setaxislim(which='y').
Example:
plt.plot([124,146,127])
sc.setylim() # Equivalent to plt.ylim(bottom=0)stackedbar
sc_plotting.stackedbar(
x=None,
values=None,
colors=None,
labels=None,
transpose=False,
flipud=False,
is_cum=False,
barh=False,
**kwargs,
)Create a stacked bar chart.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x (array) | the x coordinates of the values | required | |
| values (array) | the 2D array of values to plot as stacked bars | required | |
| colors (list/arr) | the color of each set of bars | required | |
| labels (list) | the label for each set of bars | required | |
| transpose (bool) | whether to transpose the array prior to plotting | required | |
| flipud (bool) | whether to flip the array upside down prior to plotting | required | |
| is_cum (bool) | whether the array is already a cumulative sum | required | |
| barh (bool) | whether to plot as a horizontal instead of vertical bar | required | |
| kwargs (dict) | passed to plt.bar() |
required |
Example:
values = np.random.rand(3,5)
sc.stackedbar(values, labels=['bottom','middle','top'])
plt.legend()New in version 2.0.4.
surf3d
sc_plotting.surf3d(
x=None,
y=None,
z=None,
c=None,
fig=True,
ax=None,
returnfig=False,
colorbar=None,
figkwargs=None,
axkwargs=None,
**kwargs,
)Plot 2D or 3D data as a 3D surface
Typically, x, y, and z, are all 2D arrays of the same size. However, if a single 2D array is provided, then this will be treated as z values and x and y will be inferred on a grid (or they can be provided explicitly, either as vectors or 2D arrays).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | arr |
1D or 2D array of x coordinates (or z-coordinate data if 2D and z is None) |
None |
| y | arr |
1D or 2D array of y coordinates (optional) | None |
| z | arr |
2D array of z coordinates | None |
| c | arr |
color data; defaults to match z | None |
| fig | fig |
an existing figure to draw the plot in (or set to True to create a new figure) | True |
| ax | axes |
an existing axes to draw the plot in | None |
| returnfig | bool | whether to return the figure, or just the axes | False |
| colorbar | bool | whether to plot a colorbar (true by default unless color data is provided) | None |
| figkwargs | dict | passed to plt.figure() |
None |
| axkwargs | dict | passed to plt.axes() |
None |
| kwargs | dict | passed to ax.plot_surface() |
{} |
Examples:
# Simple example
data = sc.smooth(np.random.rand(30,50))
sc.surf3d(data)
# Use non-default axes and colors
nx = 20
ny = 50
x = 10*np.arange(nx)
y = np.arange(ny) + 100
z = sc.smooth(np.random.randn(ny,nx))
c = z**2
sc.surf3d(x=x, y=y, z=z, c=c, cmap='orangeblue')New in 3.1.0: updated arguments from “data” to x, y, z, c; removed “plotkwargs” argument; “fig” defaults to True