Function Repository Resource:

MatplotlibObject

Source Notebook

Supplement Wolfram Language plotting functions with Python's Matplotlib

Contributed by: Igor Bakshee, with examples adapted from the Matplotlib documentation

ResourceFunction["MatplotlibObject"][]

returns a configured PythonObject for the submodule pyplot in Python package Matplotlib in a new Python session.

ResourceFunction["MatplotlibObject"][session]

uses the specified running ExternalSessionObject session.

ResourceFunction["MatplotlibObject"][,"func"[args,opts]]

executes the function func with the specified arguments and options.

ResourceFunction["MatplotlibObject"]["submodule"]and ResourceFunction["MatplotlibObject"][session,"submodule"]

returns a Python object for the specified submodule.

Details and Options

The Python package Matplotlib is a plotting library for the Python programming language and its many popular libraries, such as pandas.
ResourceFunction["MatplotlibObject"] sets up a configuration of the resource function PythonObject that makes working with the Python package more convenient.
In ResourceFunction["MatplotlibObject"]["submodule"] and ResourceFunction["MatplotlibObject"][session,"submodule"], the default submodule is "pyplot", which provides a state-based interface to Matplotlib.
ResourceFunction["MatplotlibObject"][Full] creates a Python object for the main matplotlib module.
For a ResourceFunction["MatplotlibObject"] p, p["FullInformation","Functions"] gives a list of the available functions and p["Information","func"] gives the signature of the specified function.
p["WebInformation"] gives a link to the ProbNum documentation that can be opened with SystemOpen.
Additional utility functions are available in the form ResourceFunction["MatplotlibObject"][obj,"func"[args,opts]], where obj can be an ExternalSessionObject session or any PythonObject p defined in the session . The utility functions include:
"Show"["fmt"]display the Python graphics
"Export"["file","fmt"]export the graphics
ResourceFunction["MatplotlibObject"][obj,"Show"["fmt"]] displays the images created in a Python session referenced by the object obj in the specified format "fmt". Available formats include: "PNG" (default), "JPG", "TIFF" and "SVG".
Graphics created in Python in the "SVG" format are imported using the resource function SVGImport.
Options for displaying Python-created graphics objects can be given as ResourceFunction["MatplotlibObject"][obj,"Show"[,opts]].
ResourceFunction["MatplotlibObject"][obj,"Export"["file.fmt"]] and ResourceFunction["MatplotlibObject"][obj,"Export"["file","fmt"]] export the graphics from Python in the specified format "fmt", which can be any format available for the Matplotlib function savefig, including "EPS", "JPEG", "PDF", "PGF", "PNG", "PS", "Raw", "RGBA", "SVG", "SVGZ" and "TIFF".
In addition to the direct use from the Wolfram Language, ResourceFunction["MatplotlibObject"] serves as a backend for plotting with the Python package NumPy, the resource function PandasObject and others.
Most of the plots defined in MatplotlibObject are also defined directly in the Wolfram Language. The use of MatplotlibObject is advantageous when bringing data to the Wolfram Language for plotting is undesirable or impractical.

Examples

Basic Examples (2) 

Construct a Matplotlib object:

In[1]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[1]=

Create a Python object representing a plot of some numbers:

In[2]:=
plt["plot"[{0, 3, 2, 1, 4}]]
Out[2]=

Add a plot label to the object:

In[3]:=
plt["title"["Some numbers"]]
Out[3]=

Show the plot as an image in the default raster format:

In[4]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[4]=

Show the plot as vector graphics:

In[5]:=
ResourceFunction["MatplotlibObject"][plt, "Show"["SVG"]]
Out[5]=

Save the plot from Python in a temporary directory, without bringing the image to your Wolfram Language session:

In[6]:=
(file1 = FileNameJoin[{$TemporaryDirectory, "line.png"}]) // FileNameTake
Out[6]=
In[7]:=
ResourceFunction["MatplotlibObject"][plt, "Export"[file1]] // FileNameTake
Out[7]=

Import the file:

In[8]:=
Import[file1]
Out[8]=
In[9]:=
Head[%]
Out[9]=

Export as a vector graphics:

In[10]:=
(file2 = FileNameJoin[{$TemporaryDirectory, "line.svg"}]) // FileNameTake
Out[10]=
In[11]:=
ResourceFunction["MatplotlibObject"][plt, "Export"[file2]] // FileNameTake
Out[11]=

Import the file:

In[12]:=
ResourceFunction["SVGImport"][file2]
Out[12]=
In[13]:=
Head[%]
Out[13]=

Clean up by deleting the temporary files and killing the Python session:

In[14]:=
DeleteFile[{file1, file2}]
In[15]:=
DeleteObject[plt["Session"]]

Plot several functions in different colors on the same plot:

In[16]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[16]=
In[17]:=
t = Range[-2., 2, .1];
In[18]:=
plt["plot"[t, Sin[t], "r"]]
Out[18]=
In[19]:=
plt["plot"[t, Cos[t], "g"]]
Out[19]=
In[20]:=
plt["plot"[t, t^2 - 2, "b"]]
Out[20]=
In[21]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[21]=

Clear the figure:

In[22]:=
plt["clf"[]]

Alternatively, create several plots with a single command:

In[23]:=
plt["plot"[t, Sin[t], t, Cos[2 t], t, Sin[2 t]]]
Out[23]=
In[24]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[24]=
In[25]:=
DeleteObject[plt["Session"]]

Scope (22) 

Basic Usage (7) 

Plot using the default image format ("PNG"):

In[26]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[26]=
In[27]:=
plt["plot"[RandomReal[1, {10}]]]
Out[27]=
In[28]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[28]=

Plot a "JPG" image:

In[29]:=
ResourceFunction["MatplotlibObject"][plt, "Show"["JPG"]]
Out[29]=
In[30]:=
DeleteObject[plt["Session"]]

Create a basic plot:

In[31]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[31]=
In[32]:=
plt["plot"[RandomReal[1, {10}]]]
Out[32]=

Export the plot by specifying the image format as filename extension:

In[33]:=
file = FileNameJoin[{$TemporaryDirectory, "line.png"}];
In[34]:=
(exported = ResourceFunction["MatplotlibObject"][plt, "Export"[file]]) // FileNameTake
Out[34]=

Print the first line of the exported file:

In[35]:=
FilePrint[exported, 1]

Export by specifying the format as a second argument:

In[36]:=
file = FileNameJoin[{$TemporaryDirectory, "line"}];
In[37]:=
(exported = ResourceFunction["MatplotlibObject"][plt, "Export"[file, "PNG"]]) // FileNameTake
Out[37]=

Check the file and delete it:

In[38]:=
FilePrint[exported, 1]
In[39]:=
DeleteFile[exported]

List file formats available for export:

In[40]:=
plt["figure"[]]["canvas"]["get_supported_filetypes"[]]
Out[40]=

Export the plot in temporary files in a few of the available formats:

In[41]:=
file = FileNameJoin[{$TemporaryDirectory, "line"}];
In[42]:=
formats = {"eps", "ps", "pdf", "svg"}
Out[42]=
In[43]:=
exported = ResourceFunction["MatplotlibObject"][plt, "Export"[file <> "." <> #, #]] & /@ formats;

Print the first line of the exported files:

In[44]:=
FilePrint[#, 1] & /@ exported
Out[44]=

Delete the temporary files:

In[45]:=
DeleteFile[exported]
In[46]:=
DeleteObject[plt["Session"]]

Plot using the default figure:

In[47]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[47]=
In[48]:=
plt["plot"[RandomReal[1, {100}]]]
Out[48]=
In[49]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[49]=
In[50]:=
DeleteObject[plt["Session"]]

Plot in two figures, starting from a sine in figure 1:

In[51]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[51]=
In[52]:=
plt["figure"[1]]
Out[52]=
In[53]:=
t = Range[0, 20, .2];
In[54]:=
sin = Sin[t];
In[55]:=
plt["plot"[t, sin]]
Out[55]=
In[56]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[56]=

Switch to a new figure 2 and plot some random numbers:

In[57]:=
plt["figure"[2]]
Out[57]=
In[58]:=
rand = RandomReal[1, {Length[t]}];
In[59]:=
plt["plot"[t, rand]]
Out[59]=
In[60]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[60]=

Switch back to figure 1 and plot points:

In[61]:=
plt["figure"[1]]
Out[61]=
In[62]:=
plt["plot"[t, sin, "s"]]
Out[62]=
In[63]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[63]=

Make similar changes in figure 2:

In[64]:=
plt["figure"[2]]
Out[64]=
In[65]:=
plt["plot"[t, rand, "s"]]
Out[65]=
In[66]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[66]=
In[67]:=
DeleteObject[plt["Session"]]

Create a figure with axes with an area where points are specified by coordinates:

In[68]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[68]=
In[69]:=
{figure, axes} = plt["subplots"[]]
Out[69]=

Draw some data on the axes:

In[70]:=
axes["plot"[{1, 2, 3, 4}, {1, 4, 2, 3}]]
Out[70]=

Show the plot:

In[71]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[71]=
In[72]:=
DeleteObject[plt["Session"]]

Create a new MatplotlibObject:

In[73]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[73]=

Prepare normally-distributed data and plot a histogram:

In[74]:=
x = RandomVariate[NormalDistribution[0, 1], {1000}];
In[75]:=
{figure, axes} = plt["subplots"[]]
Out[75]=
In[76]:=
axes["hist"[x], True]
Out[76]=
In[77]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[77]=

Adjust the plot range:

In[78]:=
axes["set"["xlim" -> {-2, 2}, "ylim" -> {0, 400}]]
Out[78]=
In[79]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[79]=
In[80]:=
DeleteObject[plt["Session"]]

Use the specified Python session:

In[81]:=
session = StartExternalSession["Python"]
Out[81]=

Create an array of normally distributed values on the Python side:

In[82]:=
arr = ResourceFunction["PythonObject"][session, "numpy.random.randn(50000)"]
Out[82]=

Create a histogram of the data:

In[83]:=
ResourceFunction["MatplotlibObject"][session]
Out[83]=
In[84]:=
%["hist"[arr], True]
Out[84]=

Show the histogram:

In[85]:=
ResourceFunction["MatplotlibObject"][session, "Show"[]]
Out[85]=

Kill the Python session:

In[86]:=
DeleteObject[session]

Plot Styles (2) 

Plot a histogram of some random numbers using the default style:

In[87]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[87]=
In[88]:=
rand = RandomVariate[NormalDistribution[0, 1], {5000}];
In[89]:=
plt["hist"[rand, "bins" -> Range[-3, 3, .1]], True]
Out[89]=
In[90]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[90]=

Clear the figure:

In[91]:=
plt["clf"[]]

Change the plot style for the histogram (one-off change):

In[92]:=
plt["hist"[rand, "bins" -> Range[-3, 3, .1], "color" -> "orange"], True]
Out[92]=
In[93]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[93]=

View some of the current style parameters (runtime configuration):

In[94]:=
rcParams = plt["rcParams", True]
Out[94]=
In[95]:=
Normal[%] // Short[#, 10] &
Out[95]=

Change one of the style settings in the current Python session to display right-hand side ticks:

In[96]:=
rcParams["Assign"["Part"["ytick.labelright"] -> True]]
Out[96]=

Clear the current figure and display the plot with y-labels on both sides:

In[97]:=
plt["clf"[]]
In[98]:=
plt["hist"[rand, "bins" -> Range[-3, 3, .1]], True]
Out[98]=
In[99]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[99]=

Restore the defaults:

In[100]:=
plt["rcdefaults"[]]

Use a predefined stylesheet:

In[101]:=
style = "_mpl-gallery";
In[102]:=
plt["style"]["use"[style]]

Show the style settings:

In[103]:=
plt["style"]["library"][style]
Out[103]=

Plot the histogram:

In[104]:=
plt["hist"[RandomVariate[NormalDistribution[0, 1], {5000}], "bins" -> Range[-3, 3, .1]], True]
Out[104]=
In[105]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[105]=
In[106]:=
DeleteObject[plt["Session"]]

List predefined stylesheets:

In[107]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[107]=
In[108]:=
styles = plt["style"]["library"] // Keys
Out[108]=

Choose a few of the styles:

In[109]:=
styles = RandomSample[styles, 8]
Out[109]=
In[110]:=
PrependTo[styles, "default"]
Out[110]=

Define a function on a grid:

In[111]:=
x = Range[-2, 2, .1];
In[112]:=
y = x^3 - .2 x^2 + x;

Plot the function using the stylesheets and display in a 3⨯3 layout:

In[113]:=
figure = plt["figure"["tight_layout" -> True]]
Out[113]=
In[114]:=
rows = 3; cols = 3;
In[115]:=
MapIndexed[Function[{style, part},
  plt["style"]["use"[style]]; axes = figure["add_subplot"[rows, cols, part[[1]]], True]; axes["plot"[x, y], True]; axes["set_title"[style], True];
  ], styles]
Out[115]=
In[116]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[ImageSize -> Large]]
Out[116]=
In[117]:=
DeleteObject[plt["Session"]]

Basic Plot Types (5) 

A line plot:

In[118]:=
x = Range[0, 10, .1];
In[119]:=
y = Sin[2 x];
In[120]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[120]=
In[121]:=
plt["plot"[x, y]]
Out[121]=
In[122]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[122]=
In[123]:=
plt["clf"[]]

A marker plot:

In[124]:=
plt["plot"[x, y, "s"]]
Out[124]=
In[125]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[125]=
In[126]:=
DeleteObject[plt["Session"]]

A scatter plot:

In[127]:=
n = 50;
In[128]:=
{x, y} = RandomReal[1, {2, n}];
In[129]:=
{sizes, colors} = RandomReal[{10, 150}, {2, n}];
In[130]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[130]=
In[131]:=
plt["scatter"[x, y, "s" -> sizes, "c" -> colors]]
Out[131]=
In[132]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[132]=
In[133]:=
DeleteObject[plt["Session"]]

A bar plot:

In[134]:=
n = 10;
In[135]:=
x = Range[n];
In[136]:=
y = RandomReal[1, n];
In[137]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[137]=
In[138]:=
plt["bar"[x, y, "width" -> 1, "edgecolor" -> "white", "linewidth" -> 2], True]
Out[138]=
In[139]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[139]=

A stem plot of the same data:

In[140]:=
plt["clf"[]]
In[141]:=
plt["stem"[x, y], True]
Out[141]=
In[142]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[142]=

A step plot:

In[143]:=
plt["clf"[]]
In[144]:=
plt["step"[x, y, "linewidth" -> 5], True]
Out[144]=
In[145]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[145]=
In[146]:=
DeleteObject[plt["Session"]]

Fill the area between two horizontal curves:

In[147]:=
n = 40;
In[148]:=
x = Range[n];
In[149]:=
y1 = 3 + 0.5 x + RandomReal[2, n];
In[150]:=
y2 = 1 + .2 x + RandomReal[2, n];
In[151]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[151]=
In[152]:=
plt["fill_between"[x, y1, "y2" -> y2, "alpha" -> .25]]
Out[152]=

Add a middle line:

In[153]:=
plt["plot"[x, (y1 + y2)/2, "linewidth" -> 2]]
Out[153]=
In[154]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[154]=
In[155]:=
DeleteObject[plt["Session"]]

Draw a stacked area plot:

In[156]:=
x = Range[0, 8, 2];
In[157]:=
y = {{1, 1.25, 2, 2.75, 3}, {1, 1, 1, 1, 1}, {2, 1, 2, 1, 2}};
In[158]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[158]=
In[159]:=
plt["stackplot"[x, y], True]
Out[159]=
In[160]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[160]=
In[161]:=
DeleteObject[plt["Session"]]

Plots of Arrays and Fields (3) 

Define a function that returns coordinate matrices constructed from from one-dimensional coordinate vectors of the same length:

In[162]:=
meshgrid[x__?VectorQ] :=
 Partition[#, Length[{x}[[1]]]] & /@ Reverse[Transpose[Tuples[Reverse[{x}]]]]

Construct coordinate matrices of a raster:

In[163]:=
{x, y} = meshgrid @@ Table[Range[-3, 3, .1], {2}];
In[164]:=
z = (1 - x/2 + x^5 + y^3) * Exp[-x^2 - y^2];

Prepare and show the raster image of the data:

In[165]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[165]=
In[166]:=
plt["imshow"[z]]
Out[166]=
In[167]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[167]=
In[168]:=
DeleteObject[plt["Session"]]

Prepare data for a 2D field of barbs:

In[169]:=
meshgrid[x__?VectorQ] :=
 Partition[#, Length[{x}[[1]]]] & /@ Reverse[Transpose[Tuples[Reverse[{x}]]]]
In[170]:=
{x, y} = meshgrid[Range[4], Range[4]];
In[171]:=
angles = {{15, 30, 35, 45}, {25, 40, 55, 60}, {35, 50, 65, 75}, {45, 60, 75, 90}} Degree // N;
In[172]:=
amplitudes = {{5, 10, 25, 50}, {10, 15, 30, 60}, {15, 26, 50, 70}, {20, 45, 80, 100}};
In[173]:=
u = amplitudes Sin[angles];
In[174]:=
v = amplitudes Cos[angles];

Draw a barbs plot:

In[175]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[175]=
In[176]:=
{fig, ax} = plt["subplots"[]]
Out[176]=
In[177]:=
ax["barbs"[x, y, u, v]]
Out[177]=

Adjust the plot range and show the plot:

In[178]:=
ax["set"["xlim" -> {0, 4.5}, "ylim" -> {0, 4.5}]]
Out[178]=
In[179]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[179]=
In[180]:=
DeleteObject[plt["Session"]]

Prepare data for streamlines of a vector flow:

In[181]:=
meshgrid[x__?VectorQ] :=
 Partition[#, Length[{x}[[1]]]] & /@ Reverse[Transpose[Tuples[Reverse[{x}]]]]
In[182]:=
{x, y} = meshgrid[Range[-3, 3, 1.], Range[-3, 3, 1.]];
In[183]:=
z = (1 - x/2 + x^5 + y^3)*Exp[-x^2 - y^2];
In[184]:=
v = Differences[z[[2 ;;, ;;]], {0, 1}];
In[185]:=
u = -Differences[z[[;; , 2 ;;]], {1, 0}];

Draw the vector flow:

In[186]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[186]=
In[187]:=
plt["streamplot"[x[[2 ;;, 2 ;;]], y[[2 ;;, 2 ;;]], u, v]]
Out[187]=
In[188]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[188]=
In[189]:=
DeleteObject[plt["Session"]]

Statistics Plots (2) 

Simulate arrival of customers to a business on different days of the month:

In[190]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[190]=
In[191]:=
d = RandomVariate[GammaDistribution[4, 1], {3, 50}];

Create and show an event plot:

In[192]:=
plt["eventplot"[d, "orientation" -> "vertical", "lineoffsets" -> {2, 4, 6}, "linewidth" -> 0.75], True]
Out[192]=
In[193]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[193]=
In[194]:=
DeleteObject[plt["Session"]]

Create a partially correlated data:

In[195]:=
x = RandomVariate[NormalDistribution[0, 1], {5000}];
y = x + RandomVariate[NormalDistribution[0, 1], {5000}]/5;

Prepare and show a density histogram:

In[196]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[196]=
In[197]:=
plt["hist2d"[x, y, "bins" -> {Range[-3, 2.9, .1], Range[-3, 2.9, .1]}], True]
Out[197]=
In[198]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[198]=
In[199]:=
DeleteObject[plt["Session"]]

Using Submodules (3) 

By default, MatplotlibObject creates a Python object for the submodule pyplot:

In[200]:=
ResourceFunction["MatplotlibObject"][]
Out[200]=

Obtain the same result by specifying the submodule explicitly:

In[201]:=
ResourceFunction["MatplotlibObject"]["pyplot"]
Out[201]=
In[202]:=
DeleteObject[#["Session"]] & /@ {%, %%}
Out[202]=

Create a PythonObject for the main matplotlib module:

In[203]:=
mpl = ResourceFunction["MatplotlibObject"][Full]
Out[203]=

List all available submodules:

In[204]:=
mpl["Information"]["Modules"]
Out[204]=
In[205]:=
DeleteObject[mpl["Session"]]

Create Python objects for the main matplotlib module, a few submodules, and the Path class in the submodule path:

In[206]:=
mpl = ResourceFunction["MatplotlibObject"][Full]
Out[206]=
In[207]:=
{plt, patches, path} = mpl /@ {"pyplot", "patches", "path.Path"}
Out[207]=

Define a list of vertices:

In[208]:=
vertices = {
  (*left,bottom*){0., 0.},
  (*left,top*){0., 1.},
  (*right,top*){1., 1.},
  (*right,bottom*){1., 0.},
  (*ignored*){0., 0.}
  }
Out[208]=

Use the created path object to define a simple shape using the standard MOVETO, LINETO and CLOSEPOLY commands:

In[209]:=
{moveto, lineto, closepoly} = path[#, True] & /@ {"MOVETO", "LINETO", "CLOSEPOLY"}
Out[209]=
In[210]:=
pth = path[All][vertices, "codes" -> {moveto, lineto, lineto, lineto, closepoly}]
Out[210]=

Prepare a figure and axes:

In[211]:=
{figure, axes} = plt["subplots"[]]
Out[211]=

Create a path patch that renders graphics primitives into a canvas and add it to the axes object:

In[212]:=
patch = patches[
  "PathPatch"[pth, "facecolor" -> "orange", "linewidth" -> 2]]
Out[212]=

Draw and display the shape:

In[213]:=
axes["add_patch"[patch]]
Out[213]=
In[214]:=
ResourceFunction["MatplotlibObject"][mpl, "Show"[AspectRatio -> 1]]
Out[214]=
In[215]:=
DeleteObject[mpl["Session"]]

Options (1) 

MatplotlibObject[plt,"Show"[]] accepts the options of Graphics:

In[216]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[216]=
In[217]:=
plt["plot"[{0, 3, 2, 1, 4}]]
Out[217]=
In[218]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[AspectRatio -> 1, Epilog -> {Red, Disk[Scaled[{.8, .25}], Scaled[.05]]}]]
Out[218]=
In[219]:=
DeleteObject[plt["Session"]]

Applications (6) 

The main use of MatplotlibObject is to plot data in Python without bringing the data to the Wolfram Language. Define a Python function and create NumPy arrays of some data points:

In[220]:=
session = StartExternalSession["Python"]
Out[220]=
In[221]:=
ExternalEvaluate[session, "import numpy as np
def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
ft1 = f(t1)
ft2 = f(t2)
ct2 = np.cos(2*np.pi*t2)
"]

Create references to the NumPy arrays without bringing them to the Wolfram Language:

In[222]:=
{t1, t2, ft1, ft2, ct2} = ResourceFunction["PythonObject"][session, "[t1,t2,ft1,ft2,ct2]", True] // Normal
Out[222]=

Create a Figure object and a subplot:

In[223]:=
plt = ResourceFunction["MatplotlibObject"][session]
Out[223]=
In[224]:=
plt["figure"[]]
Out[224]=
In[225]:=
plt["subplot"[211]]
Out[225]=

Prepare a plot of points ft1 as blue circles and points ft2 as a black line:

In[226]:=
plt["plot"[t1, ft1, "bo", t2, ft2, "k"]]
Out[226]=

Plot points ct2 as a red dashed line in another subplot:

In[227]:=
plt["subplot"[212]]
Out[227]=
In[228]:=
plt["plot"[t2, ct2, "r--"]]
Out[228]=

Display the plots created in Python:

In[229]:=
ResourceFunction["MatplotlibObject"][plt, "Show"[]]
Out[229]=
In[230]:=
DeleteObject[session]

Properties and Relations (4) 

MatplotlibObject[] gives the same result as the resource function PythonObject with a special configuration:

In[231]:=
session = StartExternalSession["Python"]
Out[231]=
In[232]:=
ResourceFunction["MatplotlibObject"][session]
Out[232]=
In[233]:=
ResourceFunction["PythonObject"][session, "matplotlib", "Configuration" -> ResourceFunction["MatplotlibObject"]]
Out[233]=
In[234]:=
DeleteObject[session]

Get information on the main module:

In[235]:=
mpl = ResourceFunction["MatplotlibObject"][Full]
Out[235]=
In[236]:=
mpl["Information"]
Out[236]=

Open the user guide in your default web browser:

In[237]:=
mpl["WebInformation"] // SystemOpen

In[238]:=
DeleteObject[mpl["Session"]]

The functions available in the pyplot module:

In[239]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[239]=
In[240]:=
Last[StringSplit[#, "."]] & /@ plt["FullInformation", "Functions"]
Out[240]=

Information on a function:

In[241]:=
plt["Information", "plot"]
Out[241]=

The web documentation for a function:

In[242]:=
plt["WebInformation", "plot"] // SystemOpen

In[243]:=
DeleteObject[plt["Session"]]

The majority of plots analogous to those in MatplotlibObject are defined directly in the Wolfram Language. Compare, for instance, DensityHistogram and hist2d:

In[244]:=
x = RandomVariate[NormalDistribution[0, 1], {5000}];
y = 1.2 * x + RandomVariate[NormalDistribution[0, 1], {5000}] / 3;
In[245]:=
DensityHistogram[Transpose[{x, y}], {{.1}, {.1}}]
Out[245]=

Set up a Python session and a MatplotlibObject:

In[246]:=
session = StartExternalSession["Python"]
Out[246]=
In[247]:=
plt = ResourceFunction["MatplotlibObject"][session]
Out[247]=

Create some data in the Python session and plot a 2D histogram in Python:

In[248]:=
{xx, yy} = ResourceFunction["PythonObject"][
  session, {"x = numpy.random.randn(5000)", "1.2 * x + numpy.random.randn(5000)/3"}, True]
Out[248]=
In[249]:=
plt["hist2d"[xx, yy, "bins" -> {Range[-3, 2.9, .1], Range[-3, 2.9, .1]}], True]
Out[249]=

Show the histogram:

In[250]:=
ResourceFunction["MatplotlibObject"][session, "Show"[]]
Out[250]=
In[251]:=
DeleteObject[session]

Possible Issues (4) 

The effect of options in MatplotlibObject[p,"Show"[,opts]] is not always the same as in the case of images created in the Wolfram Language:

In[252]:=
plt = ResourceFunction["MatplotlibObject"][]
Out[252]=
In[253]:=
{figure, axes} = plt["subplots"[]]
Out[253]=

Drawing some data and trying to display the SVG graphics on a colored background does not appear to succeed:

In[254]:=
axes["plot"[{1, 4, 2, 3}]]
Out[254]=
In[255]:=
svg = ResourceFunction["MatplotlibObject"][plt, "Show"["SVG", Background -> Orange]]
Out[255]=

Even though the background can show through if some elements of the graphics are deleted:

In[256]:=
ii = 0;
svg /. _FilledCurve /; ++ii < 3 :> {}
Out[257]=

Create background in Python instead:

In[258]:=
axes["set_facecolor"["orange"]]
In[259]:=
ResourceFunction["MatplotlibObject"][plt, "Show"["SVG"]]
Out[259]=
In[260]:=
DeleteObject[plt["Session"]]

Version History

  • 1.0.0 – 13 December 2022

Source Metadata

Related Resources

License Information