The most of examples are borrowed from this official link,

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.add_artist.html

Matplotlib.axes.Axes.add_artist

Artist tests : test a ol-line and a simple text

In [14]:
import matplotlib.lines as lines
import matplotlib.text as text

from basic_units import cm, inch # this example requires basic_units.py
import numpy as np
import matplotlib.pyplot as plt
In [21]:
fig, ax = plt.subplots()
ax.xaxis.set_units(cm)
ax.yaxis.set_units(cm)

# test a plain-ol-line
line = lines.Line2D([0*cm, 1.5*cm], [0*cm, 2.5*cm], lw=2, color='black', axes=ax)
ax.add_line(line)

t = text.Text(3*cm, 2.5*cm, 'text label', ha='left', va='bottom',  axes=ax)
ax.add_artist(t)

ax.set_xlim(-1*cm, 10*cm)
ax.set_ylim(-1*cm, 10*cm)
ax.grid(True)
ax.set_title('Artists with units')
Out[21]:
Text(0.5, 1.0, 'Artists with units')

Simple Legend02

In [22]:
import matplotlib.pyplot as plt
In [23]:
fix, ax = plt.subplots()

line1, = ax.plot([1,2,3], label='Line 1', linestyle='--')
line2, = ax.plot([3,2,1], label='Line 2', linewidth=4)

# Create a legend for the first line.
first_legend = ax.legend(handles = [line1], loc = 'upper right')

# Add the legend manually to the current Axes.
ax.add_artist(first_legend)

# Create another legend for the second line.
ax.legend(handles=[line2], loc='lower right')
Out[23]:
<matplotlib.legend.Legend at 0x1aebdd16e08>

Anchored Box01

In [24]:
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
In [26]:
fig, ax = plt.subplots(figsize=(3,3))

at = AnchoredText('Figure 1a', prop=dict(size=15), frameon=True, loc='upper left')
at.patch.set_boxstyle('round, pad=0.,rounding_size=0.2')
ax.add_artist(at)
Out[26]:
<matplotlib.offsetbox.AnchoredText at 0x1aebddee6c8>

Anchored Box03

In [30]:
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox
In [31]:
fig, ax = plt.subplots(figsize=(3, 3))

box = AnchoredAuxTransformBox(ax.transData, loc='upper left')
el = Ellipse((0, 0), width=0.1, height=0.4, angle=30)  # in data coordinates!
box.drawing_area.add_artist(el)

ax.add_artist(box)
Out[31]:
<mpl_toolkits.axes_grid1.anchored_artists.AnchoredAuxTransformBox at 0x1aebe7dcd88>

Anchored Box04

In [27]:
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (AnchoredOffsetbox, DrawingArea, HPacker, TextArea)
In [29]:
fig, ax = plt.subplots(figsize=(3, 3))

box1 = TextArea(" Test : ", textprops=dict(color="k"))
box2 = DrawingArea(60, 20, 0, 0)
el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc="r")
el2 = Ellipse((30, 10), width=16, height=5, angle=170, fc="g")
el3 = Ellipse((50, 10), width=16, height=5, angle=230, fc="b")
box2.add_artist(el1)
box2.add_artist(el2)
box2.add_artist(el3)

box = HPacker(children=[box1, box2], align="center", pad=0, sep=5)

anchored_box = AnchoredOffsetbox(loc='lower left',
                                 child=box, pad=0.,
                                 frameon=True,
                                 bbox_to_anchor=(0., 1.02),
                                 bbox_transform=ax.transAxes,
                                 borderpad=0.,
                                 )

ax.add_artist(anchored_box)

fig.subplots_adjust(top=0.8)

Automated legend creation

In [32]:
import numpy as np
np.random.seed(19680801)
import matplotlib.pyplot as plt
In [33]:
N = 45
x, y = np.random.rand(2, N)
In [35]:
x.shape
Out[35]:
(45,)
In [51]:
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)

fig, ax = plt.subplots()

scatter = ax.scatter(x, y, c=c, s=s)
print('type(scatter): ', type(scatter))

# produce a legend with the unique colors from the scatter
legend1 = ax.legend(*scatter.legend_elements(), loc='lower left', title='classes')
print('*scatter.legend_elements(): ', *scatter.legend_elements())
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop='sizes', alpha=0.6)
print('scatter.legend_elements(prop=''sizes''): ', scatter.legend_elements(prop='sizes'))
legend2 = ax.legend(handles, labels, loc='upper right', title='Sizes')
type(scatter):  <class 'matplotlib.collections.PathCollection'>
*scatter.legend_elements():  [<matplotlib.lines.Line2D object at 0x000001AEBE74CCC8>, <matplotlib.lines.Line2D object at 0x000001AEBE7B9AC8>, <matplotlib.lines.Line2D object at 0x000001AEBE733048>, <matplotlib.lines.Line2D object at 0x000001AEBE7AC248>] ['$\\mathdefault{1}$', '$\\mathdefault{2}$', '$\\mathdefault{3}$', '$\\mathdefault{4}$']
scatter.legend_elements(prop=sizes):  ([<matplotlib.lines.Line2D object at 0x000001AEBE733488>, <matplotlib.lines.Line2D object at 0x000001AEBE797108>, <matplotlib.lines.Line2D object at 0x000001AEBE743248>, <matplotlib.lines.Line2D object at 0x000001AEBE743DC8>, <matplotlib.lines.Line2D object at 0x000001AEBE779888>, <matplotlib.lines.Line2D object at 0x000001AEBE817F88>, <matplotlib.lines.Line2D object at 0x000001AEBE817C08>, <matplotlib.lines.Line2D object at 0x000001AEBE817A08>], ['$\\mathdefault{25}$', '$\\mathdefault{50}$', '$\\mathdefault{75}$', '$\\mathdefault{100}$', '$\\mathdefault{125}$', '$\\mathdefault{150}$', '$\\mathdefault{175}$', '$\\mathdefault{200}$'])
In [ ]:
 
In [ ]:
 

Anatomy of a figure

In [52]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter

np.random.seed(19680801)

X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1, aspect=1)


def minor_tick(x, pos):
    if not x % 1.0:
        return ""
    return "%.2f" % x

ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)

ax.tick_params(which='major', width=1.0)
ax.tick_params(which='major', length=10)
ax.tick_params(which='minor', width=1.0, labelsize=10)
ax.tick_params(which='minor', length=5, labelsize=10, labelcolor='0.25')

ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)

ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10)
ax.plot(X, Y2, c=(1.00, 0.25, 0.25), lw=2, label="Red signal")
ax.plot(X, Y3, linewidth=0,
        marker='o', markerfacecolor='w', markeredgecolor='k')

ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom')
ax.set_xlabel("X axis label")
ax.set_ylabel("Y axis label")

ax.legend()


def circle(x, y, radius=0.15):
    from matplotlib.patches import Circle
    from matplotlib.patheffects import withStroke
    circle = Circle((x, y), radius, clip_on=False, zorder=10, linewidth=1,
                    edgecolor='black', facecolor=(0, 0, 0, .0125),
                    path_effects=[withStroke(linewidth=5, foreground='w')])
    ax.add_artist(circle)


def text(x, y, text):
    ax.text(x, y, text, backgroundcolor="white",
            ha='center', va='top', weight='bold', color='blue')


# Minor tick
circle(0.50, -0.10)
text(0.50, -0.32, "Minor tick label")

# Major tick
circle(-0.03, 4.00)
text(0.03, 3.80, "Major tick")

# Minor tick
circle(0.00, 3.50)
text(0.00, 3.30, "Minor tick")

# Major tick label
circle(-0.15, 3.00)
text(-0.15, 2.80, "Major tick label")

# X Label
circle(1.80, -0.27)
text(1.80, -0.45, "X axis label")

# Y Label
circle(-0.27, 1.80)
text(-0.27, 1.6, "Y axis label")

# Title
circle(1.60, 4.13)
text(1.60, 3.93, "Title")

# Blue plot
circle(1.75, 2.80)
text(1.75, 2.60, "Line\n(line plot)")

# Red plot
circle(1.20, 0.60)
text(1.20, 0.40, "Line\n(line plot)")

# Scatter plot
circle(3.20, 1.75)
text(3.20, 1.55, "Markers\n(scatter plot)")

# Grid
circle(3.00, 3.00)
text(3.00, 2.80, "Grid")

# Legend
circle(3.70, 3.80)
text(3.70, 3.60, "Legend")

# Axes
circle(0.5, 0.5)
text(0.5, 0.3, "Axes")

# Figure
circle(-0.3, 0.65)
text(-0.3, 0.45, "Figure")

color = 'blue'
ax.annotate('Spines', xy=(4.0, 0.35), xytext=(3.3, 0.5),
            weight='bold', color=color,
            arrowprops=dict(arrowstyle='->',
                            connectionstyle="arc3",
                            color=color))

ax.annotate('', xy=(3.15, 0.0), xytext=(3.45, 0.45),
            weight='bold', color=color,
            arrowprops=dict(arrowstyle='->',
                            connectionstyle="arc3",
                            color=color))

ax.text(4.0, -0.4, "Made with http://matplotlib.org",
        fontsize=10, ha="right", color='.5')
Out[52]:
Text(4.0, -0.4, 'Made with http://matplotlib.org')
In [ ]: